您的位置:首页 > 产品设计 > UI/UE

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

2016-08-04 15:50 621 查看

原题链接

原题链接

解题思路

刚开始并不是很理解题意,然后去看了看讨论区的大神们。大概明白了。

对于每一个数字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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode