Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player’s turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.
This is a classic take-away game. For each number of stones, we check if there is a move (removing a square number) that leaves the opponent in a losing position. If so, the current player can win.
classSolution {
publicbooleanwinnerSquareGame(int n) {
boolean[] dp =newboolean[n+1];
for (int i = 1; i <= n; ++i) {
for (int k = 1; k*k <= i; ++k) {
if (!dp[i - k*k]) {
dp[i]=true;
break;
}
}
}
return dp[n];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funwinnerSquareGame(n: Int): Boolean {
val dp = BooleanArray(n+1)
for (i in1..n) {
for (k in1..Math.sqrt(i.toDouble()).toInt()) {
if (!dp[i - k*k]) {
dp[i] = truebreak }
}
}
return dp[n]
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defwinnerSquareGame(self, n: int) -> bool:
dp = [False] * (n+1)
for i in range(1, n+1):
k =1while k*k <= i:
ifnot dp[i - k*k]:
dp[i] =Truebreak k +=1return dp[n]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnwinner_square_game(n: i32) -> bool {
let n = n asusize;
letmut dp =vec![false; n+1];
for i in1..=n {
letmut k =1;
while k*k <= i {
if!dp[i - k*k] {
dp[i] =true;
break;
}
k +=1;
}
}
dp[n]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
winnerSquareGame(n: number):boolean {
constdp= Array(n+1).fill(false);
for (leti=1; i<=n; i++) {
for (letk=1; k*k<=i; k++) {
if (!dp[i-k*k]) {
dp[i] =true;
break;
}
}
}
returndp[n];
}
}