LeetCode OJ 之 Nim Game(翻摊游戏)

来源:互联网 发布:软件测试招聘上海 编辑:程序博客网 时间:2024/05/13 21:31

题目:

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:

  1. 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?
       和朋友玩翻摊游戏:桌子上有一堆石头,每次轮流拿1到3个石头。取走最后一个石头的算赢。你先取。你们俩都很聪明,写一个函数判断对于给定的数目的石头你是否可以赢得比赛。

思路:

        如果给定的数字n是4的倍数,那么先取者必输。假设先取者每次拿x个石头,后取者只要拿4-x个石头,那么最后一次一定是后取者拿到。比如8,无论先取者第一次拿1,2,3,只要后取者拿4-x个,就回到了题目给的4个石头的情况,这样后取者必赢。

        如果给定的数字不是4的倍数,那么先取者必赢。需要先取者首次拿n%4个石头。假设后取者每次拿y个石头,先取者在他下次只要拿4-y个石头,那么最后一次一定是先取者拿到。比如9,先取者第一次拿一个石头就变成了上面的情况。

        因此只需判断所给数字是否是4的倍数即可。

代码:

class Solution {public:    bool canWinNim(int n)     {        return n % 4;    }};



0 0
原创粉丝点击