[LeetCode]375. Guess Number Higher or Lower II

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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值