Skip to content

Commit 4e7ee2a

Browse files
Sync LeetCode submission Runtime - 479 ms (6.32%), Memory - 7.9 MB (98.33%)
1 parent 61af001 commit 4e7ee2a

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>Alice and Bob take turns playing a game, with Alice starting first.</p>
2+
3+
<p>Initially, there are <code>n</code> stones in a pile. On each player&#39;s turn, that player makes a <em>move</em> consisting of removing <strong>any</strong> non-zero <strong>square number</strong> of stones in the pile.</p>
4+
5+
<p>Also, if a player cannot make a move, he/she loses the game.</p>
6+
7+
<p>Given a positive integer <code>n</code>, return <code>true</code> if and only if Alice wins the game otherwise return <code>false</code>, assuming both players play optimally.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> n = 1
14+
<strong>Output:</strong> true
15+
<strong>Explanation: </strong>Alice can remove 1 stone winning the game because Bob doesn&#39;t have any moves.</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> n = 2
21+
<strong>Output:</strong> false
22+
<strong>Explanation: </strong>Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -&gt; 1 -&gt; 0).
23+
</pre>
24+
25+
<p><strong class="example">Example 3:</strong></p>
26+
27+
<pre>
28+
<strong>Input:</strong> n = 4
29+
<strong>Output:</strong> true
30+
<strong>Explanation:</strong> n is already a perfect square, Alice can win with one move, removing 4 stones (4 -&gt; 0).
31+
</pre>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
38+
</ul>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
int n = 1e5;
3+
array<bool, (int)1e5+1> dp;
4+
bool comp = false;
5+
6+
void precomp() {
7+
dp.fill(false);
8+
dp[1] = true;
9+
for (int i=2; i<=n; i++) {
10+
for (int s=1; s*s<=i; s++) {
11+
if (!dp[i - s*s]) {
12+
dp[i] = true;
13+
break;
14+
}
15+
}
16+
}
17+
}
18+
19+
public:
20+
bool winnerSquareGame(int n) {
21+
if (!comp) {
22+
precomp();
23+
comp = true;
24+
}
25+
26+
return dp[n];
27+
}
28+
};

0 commit comments

Comments
 (0)