292.Nim Game
Descripiton:
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.
读完这个题我有点懵。。因为不太懂这个游戏的原理。
于是就去查,发现关于Nim游戏的定义和题目中说的不太一样,Nim游戏是若干堆,而题目中是一堆。
经过进一步的查找,发现这是一个巴什博弈的题目。
于是。。。代码成了这样:
public class Solution {
public boolean canWinNim(int n) {
return (n%4!=0);
}
}
别问我为啥这么写,因为我也很绝望。。。
其实这游戏吧,如果是两个都会玩的人一起玩的话,输赢在开始确定先后顺序的时候就已经定了。
也就是说,如果这俩人用石头剪刀布决定谁先来选择出手顺序的话,石头剪刀布的结果就是游戏结果。。。
(所以为什么不直接玩石头剪刀布就好了,orz……)
姑且算完成了吧,哈哈哈==