292. Nim Game

来源:互联网 发布:视频机器码破解软件 编辑:程序博客网 时间:2024/05/01 02:37

题目

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的记录数组,再用递归的方法去求n是否能赢,这种方法在n比较小时还可以,但是空间和时间复杂度都不行。
  • 后面看了下别人的解法,这道题其实只要n%4 == 0, 则肯定返回false,因为每次一个回合敌方都可以控制下一回合的数只少4,这样最后肯定输,而当n不能被4整除且>4时,则我方可以控制对方抽取时的数肯定能被4整除,保证对方输。所以此题转化成判断n是否能被4整除

代码

我的有问题的代码(还是贴一下)

typedef enum{    LOSE = 0,    WIN,    UNDEFINE,}GAME_RESULT;class Solution {public:    bool getGameResult(vector<GAME_RESULT> &gameResult,int num)    {        //先判断之前是否已经计算出结果了        if(gameResult[num] != UNDEFINE)        {            return static_cast<bool>(gameResult[num]);        }        //递归判断,        bool result = getGameResult(gameResult,num-1) || getGameResult(gameResult,num-2) || getGameResult(gameResult,num-3);        //结果存入数组        gameResult[num] = static_cast<GAME_RESULT>(result);        return result;    }    bool canWinNim(int n) {        //退出条件        if(n <= 3)        {            return true;        }        //0为输,1赢,2初始值        vector<GAME_RESULT> gameResult(n+1,UNDEFINE);        for(size_t i=1;i<=3;i++)        {            gameResult[i] = LOSE;        }        return getGameResult(gameResult,n);    }};

正确的代码

class Solution {public:    bool canWinNim(int n) {        return n%4 != 0;    }};
0 0
原创粉丝点击