LeetCode 292.Nim Game
题意:
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.
从题意中可以大概了解到可能有规律。以为你是先拿的,所以可以先拿x个,使得剩下的stones是肯定能够是你获胜。而当最初stones的数量是这个时,那么就肯定时friend获胜。但是一次是能拿1~3个,所以胜利是以4为单位循环。也就是说,如果stones的数量能被4整除那么就是friend获胜,反之则反。
代码如下:
class Solution { public: bool canWinNim(int n) { if(n % 4 == 0) return false; else return true; } };
代码效率:
代码效率还不是和大部分人的一样,还是需要继续提高算法效率。
简化了代码:
class Solution { public: bool canWinNim(int n) { return n % 4; } };
代码效率还只是提高一点