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

Hint:

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?


[Leetcode] Nim Game题解思路及三次进阶


算法思想:
A先摸,总数为1,2,3,A胜;为4,败;总数再大,进入相同循环:只要在A摸完一次后让剩下的数目为4的倍数,A必胜,如5,6,7,A胜,8,B胜……


c代码实现:

bool canWinNim(int n) {
    if(n%4==0)return false;
    else return true;
}

[Leetcode] Nim Game-进阶第1次

public class Solution {
    public boolean canWinNim(int n) {
        // 如果一开始就是4的倍数,你就输了,因为对方可以用同样的策略
        return n % 4 != 0;
    }
}

http://segmentfault.com/a/119...
http://www.2cto.com/kf/201510...

[Leetcode] Nim Game-进阶第2次

public boolean canWinNim(int n) {
    return n>>2<<2!=n;
}

[Leetcode] Nim Game-进阶第3次

If I'm a interviewer, I prefer the candidates using burte force instead of math method.
Because it is a "coding interview", not acm/icpc or other competitions. Similar to Josephus Cycle, I prefer LinkedList Cycle than Mod-Method during interviews. Here's a backtraking-dp solution.
https://leetcode.com/discuss/...

public class Solution {
    public boolean canWinNim(int n) {
            if(n>=134882061){//I have no any other ways,please forgive my unchastity(无节操)!
               return n%4 != 0;
            }
            int[] array=new int[n+1];
            return dfs(n, array);
     }
     public boolean dfs(int n,int[] array){
         if(array[n]!=0){
             return array[n]==1?true:false;
         }
         if(n<=3){
                array[n]=1;
                return true;
            }else{
                for(int i=1;i<=3;i++){
                    if(!dfs(n-i,array)){
                        array[n-i]=-1;
                        array[n]=1;
                        return true;
                    }
                }
                array[n]=-1;
                return false;
            }
     }
}

Tips:

1.BF(BruteForce)算法是普通的模式匹配算法,BF算法的思想就是将目标串S的第一个字符与模式串T的第一个字符进行匹配,若相等,则继续比较S的第二个字符和T的第二个字符;若不相等,则比较S的第二个字符和T的第一个字 符,依次比较下去,直到得出最后的匹配结果。BF算法是一种蛮力算法。

2.约瑟夫环(Josephus Cycle)是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。通常解决这类问题时我们把编号从0~n-1,最后结果+1即为原问题的解。


afra
225 声望23 粉丝

你的努力程度之低 远还没有到比拼天赋的需要。


引用和评论

0 条评论