[LeetCode] Stone Game IV

1510. Stone Game IV

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int dp[100001][2];
bool solution(int stones, bool alice) {
if(!stones) return !alice;
if(dp[stones][alice] != -1) return dp[stones][alice];
dp[stones][alice] = !alice;
for(int i = 1; i*i <= stones and dp[stones][alice] == !alice; i++) {
if(alice) {
dp[stones][alice] |= solution(stones - i*i, !alice);
} else {
dp[stones][alice] &= solution(stones - i*i, !alice);
}
}
return dp[stones][alice];
}
public:
bool winnerSquareGame(int n) {
memset(dp,-1,sizeof(dp));
return solution(n, true);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/stone-game-iv/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.