我们正在玩一个猜数游戏,游戏规则如下: 我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。 每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。 然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。 示例: n = 10, 我选择了8. 第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。 第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。 第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。 游戏结束。8 就是我选的数字。 你最终要支付 5 + 7 + 9 = 21 块钱。
class Solution {
Long [][] memo;
/**
记忆化递归
*/
public int getMoneyAmount(int n) {
memo=new Long[n+1][n+1];
return (int)helper(1,n);
}
public long helper(int low,int high){
if(low>=high){//猜对了 或者越界
return 0;
}
if(memo[low][high]!=null){
return memo[low][high];
}
long min=Integer.MAX_VALUE;
long res=0;
for(int i=low;i<=high;i++){
res=( i+Math.max(helper(low,i-1),helper(i+1,high)) );//一定要最大值,满足两者才可以
min=Math.min(min,res);
}
memo[low][high]=min;
return min;
}
}