#292.Nim游戏
找到数学规律:
class Solution {
public:
bool canWinNim(int n) {
int base=3;
if(n%(base+1)==0){
return false;
}
else{
return true;
}
}
};
也可以用博弈的动态规划思想:
状态转移方程:
f(n) = !(f(n-1) && f(n-2) && f(n-3))
f(0) = false
#375.猜数字大小II
动态规划又可以解这道题:
题目:
我们正在玩一个猜数游戏,游戏规则如下:
我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。
每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。
然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。
给定 n ≥ 1,计算你至少需要拥有多少现金才能确保你能赢得这个游戏。
暴力解法:
如果我们选择 ii 作为第一次尝试,总体最小代价是
public class Solution {
public int calculate(int low, int high) {
if (low >= high)
return 0;
int minres = Integer.MAX_VALUE;
for (int i = low; i <= high; i++) {
int res = i + Math.max(calculate(i + 1, high), calculate(low, i - 1));
minres = Math.min(res, minres);
}
return minres;
}
public int getMoneyAmount(int n) {
return calculate(1, n);
}
}