题目链接: https://leetcode.com/problems/guess-number-higher-or-lower-ii/
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.
Hint:
思路: 题目是让求得最少需要多少钱可以保证一定能赢, 也就是最坏情况下需要最少多少钱. 依然利用二分查找的思想, 当我们猜X时, 如果错了, 那么需要往左右两端继续查找, 那么最大代价即为 dp[i][j] = min(dp[i][j], X + max(dp[i][X-1], dp[X+1][j]));
这样要计算在1-n之间的最大代价, 只要枚举每一个数即可.
可以利用分治+记忆化搜索来做, 也可以使用动归.
代码如下:
class Solution {
public:
int DFS(vector> &dp, int left, int right)
{
if(left >= right) return 0;
if(dp[left][right]) return dp[left][right];
int ans = INT_MAX;
for(int i = left; i <= right; i++)
ans = min(ans, i + max(DFS(dp, left, i-1), DFS(dp, i+1, right)));
return dp[left][right]=ans;
}
int getMoneyAmount(int n) {
if(n ==0) return 0;
vector> dp(n+1, vector(n+1, 0));
return DFS(dp, 1, n);
}
};
class Solution {
public:
int getMoneyAmount(int n) {
if(n ==0) return 0;
vector> dp(n+1, vector(n+1, 0));
for(int i = n-1; i > 0; i--)
{
for(int j = i+1; j <=n; j++)
{
int ans = INT_MAX;
for(int k = i; k