1.Question
- Total Accepted: 18911
- Total Submissions: 53226
- Difficulty: Medium
- Contributor: LeetCode
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.
However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.
Example:
n = 10, I pick 8. First round: You guess 5, I tell you that it's higher. You pay $5. Second round: You guess 7, I tell you that it's higher. You pay $7. Third round: You guess 9, I tell you that it's lower. You pay $9. Game over. 8 is the number I picked. You end up paying $5 + $7 + $9 = $21.
Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.
class Solution {
public:
int getMoneyAmount(int n) {
int dp[n+1][n+1] = {0};
for(int i = n; i > 0; i--)
for(int j = i + 1; j <= n; j++)
{
dp[i][j] = i + dp[i+1][j]; //初始化dp[i][j],相当于k=i
for(int k = i + 1; k < j; k++) //k从i+1到j-1
dp[i][j] = min(dp[i][j], k + max(dp[i][k-1], dp[k+1][j]));
dp[i][j] = min(dp[i][j], j + dp[i][j-1]); // k = j
}
return dp[1][n];
}
};
3.Note
1. 这个题的意思是,在1~n这个区间猜出一个数字,最少需要消耗多少钱,有个细节要注意,在k~k之间只有1个数,这时候是不需要消耗钱的。这个题用DP做,是一个min max的问题,和摔鸡蛋的问题有相似之处。 对于区间[i, j], 猜 k 的话,那么需要消耗的钱数是k+max( dp[i][k-1], dp[k+1][j]),那么最小的消耗就是 min(k+max( dp[i][k-1], dp[k+1][j])), k = i,...,j。注意这里的边界处理,当k=i或者j的时候,写程序的时候是需要另外处理的,详情见代码。