LeetCode 292: Nim Game 题解

别看题这么长,其实很简单。


LeetCode 292: Nim Game

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.


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.


这道题的意思是,两个人做游戏,给 n 个石头,每个人每次可以拿走1-3个石头,最后拿掉所有剩下石头的人获胜。例如,有4个石头,如果A先拿,那么A可以拿1个,2个或者3个,则B无论如何都能获胜。

题目要求:给定 n 个石头,每次都是你先拿,判断你能不能获胜。

题解:这种题一般都有规律,我们可以列举前面的几种情况来观察是否有规律可循:

nwin?
1YES
2YES
3YES
4NO
5YES
6YES
7YES
8NO
9YES
10YES
11YES
12NO


发现规律了吗? 没错,只要 n 是4的倍数,那么你就会输。n=1,2,3,4 的时候就不用解释了,来看看后面的:

n等价于
4你不管拿1,2还是3个,剩下3,2,1个都能被B一次拿完,你一定输
5你先拿1个,n-1=4,轮到B拿,他一定输
6你先拿2个,n-2=4,轮到B拿,他一定输
7你先拿3个,n-3=4,轮到B拿,他一定输
8你不管拿1,2还是3个,剩下7,6,5个,参考上面三行,最后都能被B拿完,你一定输
9你先拿1个,n-1=8,轮到B拿,他一定输
10你先拿2个,n-2=8,轮到B拿,他一定输
11你先拿3个,n-3=8,轮到B拿,他一定输
12你不管拿1,2还是3个,剩下11,10,9个,参考上面三行,最后都能被B拿完,你一定输


所以,只要 n <script type="math/tex" id="MathJax-Element-5">n</script> 为4的倍数,你一定会输,这些代码就很简单了,通过的代码如下:

bool canWinNim(int n) {
    if(0 == n % 4)
        return false;
    else
        return true;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页