87. Nim Game

来源:互联网 发布:淘宝津贴200是什么意思 编辑:程序博客网 时间:2024/06/15 16:44

-292. Nim Game My Submissions QuestionEditorial Solution
Total Accepted: 71375 Total Submissions: 134218 Difficulty: Easy
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个石头,最后拿走石头的人赢,这是一个游戏博弈的题

策略:
如果
1.n%4==0 先手 输(先手拿m个,后手拿4-m个)
2.n%4==1 先手赢 (先手拿1个,转化为1, 那先手成为后手)
3.n%4==2 先手赢 (同2)
4.n%4==3 先手赢 (同2)

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