LeetCode 375. Guess Number Higher or Lower II
原题链接: https://leetcode.com/problems/guess-number-higher-or-lower-ii/
Minimax思想。利用DP。Dp[i][j]表示在[i,j]范围内保证能赢的钱数。在[1, n]的范围中,我取一个数k,这样就被分为了[1, k-1], [k],[k+1, n]这三段。由于事先并不知道target坐落在哪个范围,既然要保证能赢,那么取Max(dp[1, k-1], dp[k, k], dp[k+1, n])。然后在众多k中选取cost最小的。
public class Solution {
public int getMoneyAmount(int n) {
int [][]dp = new int[n+1][n+1];
return calculate(dp, 1, n);
}
private int calculate(int[][]dp, int start, int end){
if(start >= end){
return 0;
}
if(dp[start][end] != 0){
return dp[start][end];
}
int current_pay = Integer.MAX_VALUE;
for(int i = start; i <= end; i++){
int pay = i + Math.max(calculate(dp, start, i-1), calculate(dp, i+1, end));
current_pay = Math.min(current_pay, pay);
}
dp[start][end] = current_pay;
return current_pay;
}
}