Skip to content

Commit 10ae06c

Browse files
authored
Create subtree-removal-game-with-fibonacci-tree.cpp
1 parent d03109c commit 10ae06c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
bool findGameWinner(int n) {
7+
return n % 6 != 1; // the cycle period is 6 observed from solution2, which could be proved by mathematical induction
8+
}
9+
};
10+
11+
// Time: O(n)
12+
// Space: O(1)
13+
class Solution2 {
14+
public:
15+
bool findGameWinner(int n) {
16+
vector<int> grundy = {0, 1};
17+
for (int i = 2; i < n; ++i) {
18+
grundy[i % 2] = (grundy[(i - 1) % 2] + 1) ^ (grundy[(i - 2) % 2] + 1);
19+
}
20+
return grundy[(n - 1) % 2]; // colon principle, replace the branches by a non-branching stalk of length equal to their nim sum
21+
}
22+
};

0 commit comments

Comments
 (0)