375. Guess Number Higher or Lower II
- Total Accepted: 1546
- Total Submissions: 5408
- Difficulty: Medium
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
题解转自:
http://blog.csdn.net/adfsss/article/details/51951658
题目大意还是猜数游戏,不过这次的重点换了,题目要求你猜错了就得付与你所猜的数目一致的钱,最后应求出保证你能赢的钱数(即求出保证你获胜的最少的钱数),题目的提示是动态规划,自己吃的不太透,想着之前做过的动态规划都是从初始条件出发,再推出后面的值,于是就噗嗤噗嗤地写了前面几种情况在找规律,算了下,发现max(后四位的所应判断的钱数,倒数第四位的钱数+前面的钱数)好像挺有可能的,但提交的时候发现n大于19时就统统过不了了,于是果断否决了自己的想法,因为找规律这个想法完全说服不了自己为什么这样求出的是最小值,在这里也给自己敲了一个警钟,不要试图用侥幸的心理来蒙骗自己,网上了搜一番后,发现没有讲的比较清楚的博客,统统都是贴代码(っ*´Д`)っ(理解不了了喂),后面在leetcode的discuss里面有两句英文让自己一下子就懂了.
具体是这样的,在1-n个数里面,我们任意猜一个数(设为i),保证获胜所花的钱应该为 i + max(w(1 ,i-1), w(i+1 ,n)),这里w(x,y))表示猜范围在(x,y)的数保证能赢应花的钱,则我们依次遍历 1-n作为猜的数,求出其中的最小值即为答案,即最小的最大值问题
转:
http://blog.csdn.net/xiaxiazls/article/details/50018225
定义并初始化二维数组 vector<vector <int> > ivec(m ,vector<int>(n,0)); //m*n的二维vector,所有元素初始化为0
1 class Solution { 2 public: 3 int getMoneyAmount(int n) { 4 //vector<vector <int> > ivec(m ,vector<int>(n,0)); //m*n的二维vector,所有元素初始化为0 5 vector<vector <int> > dp(n + 1 ,vector<int>(n + 1, INT_MAX)); //n*n的二维vector,所有元素初始化为INT_MAX 6 dfs(dp,1,n); 7 return dp[1][n]; 8 } 9 int dfs(vector<vector <int> > &dp,int l,int r){ 10 if(dp[l][r] != INT_MAX){ 11 return dp[l][r]; 12 } 13 if(l == r){ 14 return dp[l][r] = 0; 15 } 16 if(l + 1 == r){ 17 return dp[l][r] = l; 18 } 19 int i; 20 for(i = l + 1;i <= r - 1;i++){ 21 dp[l][r] = min(dp[l][r],i + max(dfs(dp,l,i - 1),dfs(dp,i + 1,r) ) ); 22 } 23 return dp[l][r]; 24 } 25 };