LeetCode 375. Guess Number Higher or Lower II

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值