problem:
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
tip:
博弈类问题:桌上一堆石子,两个人轮流取,每次取[1-3]个,桌上不同数量的石子判断第一个人的输赢情况。
考虑边界问题,每次最少取1个,最多取3个,谁先拿球谁赢,如果想获胜,必须确保:自己第一次拿走一些石子后,在剩下的石子中,自己均有一定的策略拿走与之对应数目的石子。只考虑边界情况(1+3=4),只要对方拿走x个,自己则拿走4-x个,这样每一轮会拿走4个球,最终剩下的即是第一个人拿走的数量即可保证获胜。
程序实现比较简单,但是思想很有意思。
solution:
class Solution {
public:
bool canWinNim(int n) {
return n%4;
}
};