Guess Number Higher or Lower II

来源:互联网 发布:上海java招聘会 编辑:程序博客网 时间:2024/06/05 11:20

Description
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.

解题思路:使用动态规划的方法做这道题,可以这样子切入题目,我们要计算出在(1,n)中猜出特定的数需要的最少的罚金,假如第一次选择的数为x,如果特定的数比x小,那么下一次只在(1,x-1)中挑选就可以,如果特定的数比x大,那么下一次就应该在(x+1,n)里面挑选,如果刚好等于x,游戏结束。为了保证钱足够,我们要做最坏的假设,就是这个特定的数落在罚钱罚得比较多的一边,假定dp(i,j)表示你需要的钱数来保证能在(i,j)中找出特定的数,当选择了x之后,dp(i,j)=x+max(dp(i,x-1),dp(x+1,j))。然而这个x要怎样选择呢,这里使用的方法是把x的所有选择的可能都试一次,使得dp(i,j)最小的那个就是我们要的答案。程序代码如下:

class Solution {public:    int cal(vector<vector<int>> & dp, int s, int e) {        if (s >= e)            return 0;        if (dp[s][e] != 0)            return dp[s][e]; //优化时间复杂度        for (int i = s; i <= e; i++) {            if (dp[s][e] != 0)                dp[s][e] = min(dp[s][e], i + max(cal(dp, s, i - 1), cal(dp, i + 1, e)));            else                dp[s][e] = i + max(cal(dp, s, i - 1), cal(dp, i + 1, e));        }        return dp[s][e];    }    int getMoneyAmount(int n) {        vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));        int result = cal(dp, 1, n);        return result;    }};
0 0
原创粉丝点击