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

题目链接: 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. S e c o n d r o u n d : Y o u g u e s s 7 , I t e l l y o u t h a t i t s h i g h e r . Y o u p a y 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];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36946274/article/details/81390651