你正在和朋友进行Nim博弈:桌子上有一堆石头,每一次你们都会从中拿出1到3个石头。拿走最后一个石头的人赢得博弈。博弈开始时,你是先手。
假设两个人都绝对理性,都会做出最优决策。给定石头的数量,判断你是否会赢得比赛。
举例:有四个石头,那么你永远不会赢得比赛。不管拿几个,最后一个石头一定会被你的朋友拿走。
样例
样例 1:
输入:n = 4
输出:False
解析:先手取走1,2或者3,对方都会取走最后一个
样例 2:
输入:n = 5
输出:True
解析:先手拿1个,必胜
解题思路1:
第一眼就想到用动态规划。设dp[i]为剩i个石头时,能否赢。
最后一步:只能有扔1个石头,2个石头,3个石头这三种情况
子问题:若扔掉1-3块石头之后,即dp[i-1],dp[i-2],dp[i-3]代表对方的输赢情况,若其中中有一个赢,则dp[i]输,若其中全为输,则dp[i]赢。
状态方程:dp[i] = !dp[i-1] || !dp[i-2] || !dp[i-3]
初始条件:dp[1] = true, dp[2] = true, dp[3] = true
public class Solution {
/**
* @param n: an integer
* @return: whether you can win the game given the number of stones in the heap
*/
public boolean canWinNim(int n) {
// Write your code here
//dp[i]为剩i个石头时,能否赢
boolean[] dp = new boolean[n+1];
//初始条件
dp[0] = false;
if(n >= 1)
dp[1] = true;
if(n >= 2)
dp[2] = true;
if(n >= 3)
dp[3] = true;
//状态方程
for(int i=4; i<n+1; i++){
dp[i] = !dp[i-1] || !dp[i-2] || !dp[i-3];
}
return dp[n];
}
}
可能会出现特别大的n导致内存溢出,所以采用取余优化内存,因为每次新状态只与前三个状态有关,所以对4取余即可。
public class Solution {
/**
* @param n: an integer
* @return: whether you can win the game given the number of stones in the heap
*/
public boolean canWinNim(int n) {
// Write your code here
boolean[] dp = new boolean[4];
if(n >= 1)
dp[1] = true;
if(n >= 2)
dp[2] = true;
if(n >= 3)
dp[3] = true;
for(int i=4; i<=n; i++)
dp[i%4] = !dp[(i-1)%4] || !dp[(i-2)%4] || !dp[(i-3)%4];
return dp[n%4];
}
}
解题思路2:
发现规律,只有4及4的倍数才会输。
public class Solution {
/**
* @param n: an integer
* @return: whether you can win the game given the number of stones in the heap
*/
public boolean canWinNim(int n) {
// Write your code here
return n%4 != 0;
}
}