Nim Game 解答

时间:2021-05-19 08:50:15

Question

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

Hint:

  1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

Solution 1 -- DP

传统的方法是DP。我们认为比赛只有两个状态:win, not win

F(x) = (!F(x - 1)) || (!F(x - 2)) || (!F(x - 3))

当对手不是全赢时,玩家即是赢。

Time complexity O(n), space cost O(1)

 public class Solution {
public boolean canWinNim(int n) {
boolean first = true, second = true, third = true;
for (int i = 3; i < n; i++) {
boolean tmp = (!first) || (!second) || (!third);
first = second;
second = third;
third = tmp;
}
return third;
}
}

Solution 2 -- Math

这道题其实是个数学问题。根据Discuss上的帖子,有一个结论:

Theorem: The first one who got the number that is multiple of 4 (i.e. n % 4 == 0) will lost, otherwise he/she will win.

1. Base case

When number = 4, the player loses.

2. Induction

Hypothesis: we assume that number = 4 * k, the player will lose.

When number = 4 * (k + 1), after the player moves stones, the number becomes (4 * k + 3) or (4 * k + 2) or (4 * k + 3). So the advisor can always make number for next round to be 4 * k. Thus, the player will lose.

 public class Solution {
public boolean canWinNim(int n) {
return !((n % 4) == 0);
}
}