题目描述
我们正在玩一个猜数游戏,游戏规则如下:
我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。
每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。
然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。
示例:
n = 10, 我选择了8.
第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。
第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。
第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。
游戏结束。8 就是我选的数字。
你最终要支付 5 + 7 + 9 = 21 块钱。
总结
抽象的数组往往拥有抽象的排列,就像这题的DP:
在判断(1, 3)的数时,Math.max调用的是(1,0)(2,3)和(1, 1)(3, 3),即“前半段”是横向循环,“后半段”是竖向循环。
暴力二分法(超时)
public class Solution {
public int getMoneyAmount(int n) {
return calculate(1, n);
}
public int calculate(int low, int high) {
if (low >= high)
return 0;
int minres = Integer.MAX_VALUE;
for (int i = (low+high) / 2; i <= high; i++) {
int res = i + Math.max(calculate(i+1, high), calculate(low, i-1));
minres = Math.min(res, minres);
}
return minres;
}
}
DP
以 i 为第一次尝试找到最小开销的过程可以被分解为找左右区间内最小开销的子问题。对于每个区间,我们重复问题拆分的过程,得到更多子问题
注意:这张图下标为零的地方没有画出来
class Solution {
public int getMoneyAmount(int n) {
int[][] dp = new int[n+1][n+1];
for(int len = 2; len <= n; len++) {
for(int start = 1; start <= n - len + 1; start++) {
int res = Integer.MAX_VALUE; // len:3,start:1,piv:2
for(int piv = start; piv < start + len - 1; piv++) {
int min = piv + Math.max(dp[start][piv-1], dp[piv+1][start+len-1]);
res = Math.min(res, min);
}
dp[start][start+len-1] = res;
}
}
return dp[1][n];
}
}
优化DP
class Solution {
public int getMoneyAmount(int n) {
int[][] dp = new int[n+1][n+1];
for(int len = 2; len <= n; len++) {
for(int start = 1; start <= n - len + 1; start++) {
int res = Integer.MAX_VALUE;
// 下面是唯一改动的地方
for(int piv = start + (len - 1) / 2; piv < start + len - 1; piv++) {
int min = piv + Math.max(dp[start][piv-1], dp[piv+1][start+len-1]);
res = Math.min(res, min);
}
dp[start][start+len-1] = res;
}
}
return dp[1][n];
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/guess-number-higher-or-lower-ii