LeetCode 292. Nim game (python)

Topic Link

Subject description:

You and your friends, two people to play with Nim game: a pile of stones on the table, every time you turn remove 1--3 stones. Removed the last stone of the person is the winner. As you just get.

You are a wise man, every step is the optimal solution. Write a function to determine whether you can win the game, given the number of stones.

Example:

Input: 4
Output: false
explanation: if there are four stone heap, then you will never win;
because whether you take away one, two or three stones, last stone will always be to get your friends go.

Problem-solving ideas:

If the stone heap only one, two, or three stones, then your turn, you can put all the stones away, so to win in the game. And if the title as described above, there are just four stone heap, you will fail. Because in this case no matter how much you take away the stone, always leave a few for your opponent, so that he can beat you in the game. Therefore, in order to win, in your turn, you must avoid several stones stone heap is four.

Likewise, if there are five, six, or seven stones, you can control the number of pick your own stone, always give your opponent just four stones left to make him lose the game. But if there are eight stone rock pile, you will inevitably lose, because whether you pick out one, two or three from a pile of stones, your opponent can choose three, two or one to ensure that once again your turn, you'll face four stones.

Obviously, the same pattern it is repeated n = 4,8,12,16, ..., it can be seen basically a multiple of 44.

class Solution:
    def canWinNim(self, n: int) -> bool:
        return n%4!=0

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/91907401