You were playing the following Nim Game with your friend:there was a heap of stones on the table and each time one of your take Turns to remove 1 to 3 stones. The one who removes, the last stone would be the winner. You'll take the first turn to remove the stones.
Both of you is very clever and has optimal strategies for the game. Write a function to determine whether your can win the game given the number of stones in the heap.
For example, if there is 4 stones in the heap and then you'll never win the Game:no matter 1, 2, or 3 stones you remove, The last stone is always being removed by your friend.
Hint:
- If There is 5 stones in the heap, could your figure out a-a-to-remove the stones such that you'll always be the winner ?
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
The least amount of code in the history of the solution, although the solution is very simple, but the topic is quite interesting, the topic said to us a heap of stones, each can take a two or three, two people take turns, get the last stone people win, now give us a heap of stones, ask us whether we can win. Then we analyze from the very beginning, because we first take, then 3 within (including 3) of the stones, we directly win, if a total of 4, then we must lose, because no matter we take a few, the next person can be taken out at once. If a total of 5, we win, because we can take one, and then become 4 to let others take, according to the above analysis we win, so we list 1 to 10 cases are as follows:
1 Win
2 Win
3 Win
4 Lost
5 Win
6 Win
7 Win
8 Lost
9 Win
Ten Win
Thus we can find the law, as long as 4 times the number of, we will lose, so for 4 to get more, see the code is as follows:
class Solution {public: bool canwinnim (int n) { return 4; }};
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Nim Game Nim Games