leetcode 375. Guess Number Higher or Lower II 解题报告

来源:互联网 发布:js把字符串转成数组 编辑:程序博客网 时间:2024/05/13 03:03

原题链接

原题链接

解题思路

刚开始并不是很理解题意,然后去看了看讨论区的大神们。大概明白了。
对于每一个数字x在数组[i~j],我们算他的花费为 x + max{DP([i~x-1]), DP([x+1, j])}。
the max意思是无论你猜哪个数字,这个数字的反馈都是最差的,需要花费很多。
the min是指在这么多最差反馈里挑出最少的花费。
数组dp[i][j] 表示i~j的minmax花费。

解题代码

public class Solution {    public int getMoneyAmount(int n) {        int[][] dp = new int[n+1][n+1];        return DP(dp,1,n);    }    public int DP(int[][] dp,int low,int high) {        if(high <= low) {            return 0;        }        if(dp[low][high] != 0) {            return dp[low][high];        }        int res = Integer.MAX_VALUE;        for (int i = low;i <= high;i++) {            int tmp = i + Math.max(DP(dp,low,i-1),DP(dp,i+1,high));            res = Math.min(tmp,res);        }        dp[low][high] = res;        return res;    }}
1 0
原创粉丝点击