https://leetcode.com/problems/guess-number-higher-or-lower-ii/
二维DP,dp[i][j]表示从i~j里面找一个数的最大cost,因此dp[i][i] = 0。dp[beg][end]为遍历beg~end,dp[beg][end] = Math.min(dp[beg][end], i + Math.max(partition(beg, i - 1), partition(i + 1, end))。这里面的dp[beg][end]求min,不要忘了要赋初始值为MAX_VALUE!!!
public class Solution {
public int getMoneyAmount(int n) {
int[][] dp = new int[n + 1][n + 1];
return partition(dp, 1, n);
}
private int partition(int[][] dp, int beg, int end) {
if (beg >= end) {
return 0;
} else if (dp[beg][end] != 0) {
return dp[beg][end];
}
int res = Integer.MAX_VALUE;
int tmp = 0;
// 一定要从beg开始,业务上来讲就是取值i的范围包括beg和end
for (int i = beg; i <= end; i++) {
tmp = i + Math.max(partition(dp, beg, i - 1), partition(dp, i + 1, end));
res = Math.min(res, tmp);
}
dp[beg][end] = res;
return res;
}
}