思路:设f[l][r]表示从范围l~r中猜到正确数字所需要的最小现金数。假设本次在范围l~r中猜x,对其进行分析,可得猜x的最小现金数为: max(f[l][x-1],f[x+1][r])+x。f[l][r]的值为所有猜x的最小现金数中最小的那个。
代码:
class Solution {
public int getMoneyAmount(int n) {
int[][] f = new int[n+2][n+2];
for(int len=2;len<=n;len++){
for(int l=1;l+len-1<=n;l++){
int r=l+len-1;
f[l][r]=Integer.MAX_VALUE;
for(int x=l;x<=r;x++){
int c=Math.max(f[l][x-1],f[x+1][r])+x;
f[l][r]=Math.min(f[l][r],c);
}
}
}
return f[1][n];
}
}