[leetcode]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.

Example:

Input: 4
Output: false
Explanation: 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.

解法

思路

这个题其实出的。挺。无。语。的。感觉作者的本意是让用动态规划做,然后这个题呢。。其实就一个规律。。。。

代码一

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

代码二

我把动态规划的代码也写出来,但是超时了。。

class Solution {
    public boolean canWinNim(int n) {
        if(n < 4) return true;
        boolean dp1 = true;
        boolean dp2 = true;
        boolean dp3 = true;
        for(int i = 4; i <= n; i++) {
            boolean temp = !(dp1 && dp2 && dp3);
            dp1 = dp2;
            dp2 = dp3;
            dp3 = temp;
        }
        return dp3;
    }
}
posted @ 2018-10-17 09:36  shinjia  阅读(100)  评论(0编辑  收藏  举报