Tuesday, June 6, 2017

292. Nim Game

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.



Solution:

Method 1: Math Formula

Simply write down 1, 2, 3, 4, ... check the sequence and find the law.

1 T
2 T
3 T
4 F
5 T
6 T
7 T
8 F
9 T
....

We find that if n % 4 != 0, the first player can always win.



Code:


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



Method 2: Dynamic Programming

This is a more general method.

Given n stones, whether the first player can win depends on whether the second player can win with n - 1, n - 2, or n - 3 stones.


Code:


public class Solution {
    public boolean canWinNim(int n) {
        if (n <= 3) {
            return true;
        }
        boolean[] canWin = new boolean[n + 1];
        canWin[1] = true;
        canWin[2] = true;
        canWin[3] = true;
        for (int i = 4; i <= n; i++) {
            canWin[i] = !canWin[i - 1] || !canWin[i - 2] || !canWin[i - 3];
        }
        return canWin[n];
    }
}