375. Guess Number Higher or Lower II

题目链接:https://leetcode.com/problems...

又是一道dp的题,关键是找subproblem。dp[i][j]表示最少的money you need to guarantee a win,当范围是(i+1, j+1)的时候。所以要求dp[i][j]就应该遍历切分点找出最小的值,这个切分点可能把问题分成左边或者右边,要取最大值才能保证所有的值都能赢。所以
dp[i][j] = min(k+1 + max(dp[i][k-1], dp[k+1][j]))
注意base case:dp[i][i] = 0, dp[i][i+1] = i + 1

public class Solution {
    public int getMoneyAmount(int n) {
        int[][] dp = new int[n][n];
        for(int i = 0; i < n - 1; i++) dp[i][i+1] = i + 1;
        
        for(int len = 2; len < n; len++) {
            for(int i = 0; i + len < n; i++) {
                int j = i + len;
                for(int k = i + 1; k < j; k++) {
                    int cur = k + 1 + Math.max(dp[i][k-1], dp[k+1][j]);
                    if(dp[i][j] == 0 || dp[i][j] > cur) dp[i][j] = cur;
                }
            }
        }
        return dp[0][n-1];
    }
}

lulouch13
13 声望6 粉丝