题目链接: 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:
- The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in thefirst scenario.
- Take a small example (n = 3). What do you end up paying in the worst case?
- Check out this article if you're still stuck.
- The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming.
- As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?
思路: 题目是让求得最少需要多少钱可以保证一定能赢, 也就是最坏情况下需要最少多少钱. 依然利用二分查找的思想, 当我们猜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<vector<int>> &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<vector<int>> dp(n+1, vector<int>(n+1, 0));
return DFS(dp, 1, n);
}
};
class Solution {
public:
int getMoneyAmount(int n) {
if(n ==0) return 0;
vector<vector<int>> dp(n+1, vector<int>(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 <j; k++)
ans = min(ans, k + max(dp[i][k-1], dp[k+1][j]));
dp[i][j] = ans;
}
}
return dp[1][n];
}
};

这篇博客解析了LeetCode的375题,讨论如何在猜数字游戏中以最小成本确保胜利。通过采用动态规划和二分查找策略,分析了最佳游戏策略,即最小化可能的最大损失。博主提供了问题的思路和代码实现,并探讨了如何修改代码来解决预期损失最小化的问题。

494

被折叠的 条评论
为什么被折叠?



