原题链接: https://leetcode.com/problems/nim-game/
1. 题目介绍
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.
你和另外一个小伙伴玩Nim游戏,这个游戏的规则是这样的:有一堆石头在桌子上,你们两个人轮流从中拿1~3个石子,拿走最后一个石子的人就是胜利者。你是第一个拿石子的人。
两个人都会采取对自己最有利的策略拿石子,写出一个函数计算你是否能赢。
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.
2. 解题思路
这个题是一个博弈论的题目。
根据题意,每人每步最多拿走3个石子,所以石子的总数至少为 4 。当石子的总数为 4 的时候,不管先手拿走几个石子,后手都有应对的方法,先手必输。
而且8个石子也是必输,因为8个石子可以分成两个部分,每个部分4个石子。自然先手还是必输。进一步可以推出,如果石子的总数是4的倍数,那么先手必输。
当石子的总数为5个的时候,先手先拿走一个石子,这样的话,后手就等于是在4个石子的情况下充当先手,自然后手必输。而6个、 7个石子时,先手都可以先拿走2个石子或者3个石子来让后手落入4个石子的陷阱。
所以我们可以看出,当石子的总数不是4的倍数的时候,先手必赢。
实现代码
class Solution {
public boolean canWinNim(int n) {
return ( n%4 == 0 ? false : true);
}
}