LeetCode Problem -- 292. Nim Game

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/85331121
  • 描述:

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
Explanation: 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个物品,两个人轮流从这堆物品中取物, 规定每次至少取一个,最多取m个。最后取光者得胜。
    最终得出的结论是,当物品数目n是m+1的整数倍时,先手者必输。
  • 思路一:既然题中‘我’为先手者,且每次最多取3个,则只需判断n%4的值即可。
class Solution {
public:
    bool canWinNim(int n) {
        return n % 4;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/85331121
今日推荐