码迷,mamicode.com
首页 > 其他好文 > 详细

Guess Number Higher or Lower II--困惑

时间:2017-01-05 01:38:35      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:time   leetcode   money   而且   eth   get   技术分享   from   区间   

今天,试着做了一下LeetCode OJ上面的第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.
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):

dp[p][q]表示猜数的范围在p-q之间要保证赢需要的最小花费。此题为:dp[1][n].

思路一:

假设我们随意猜的数为k,

dp[1][n] = k + max{dp[1][k-1],dp[k+1][n]},

如此,最后得到了一个值,此值为在1-n区间猜数保证赢所需要的最小花费(最大花费?)。

在此过程中,我们不断的在寻求每个区间的最大花费,这样会不会导致所猜的数一直在改变,感觉这样求出的最大就太大了,而且也没有什么意义。

默默的感觉是自己想错了,所猜的数没有在变?

还有一个问题是:假设所猜的数不变,那么如果一直取子区间所需要的最大花费,那么最小又从哪里体现呢?

思路二:

在1-n个数里面,我们任意猜一个数(设为i),保证获胜所花的钱应该为 i + max(w(1 ,i-1), w(i+1 ,n)),这里w(x,y))表示猜范围在(x,y)的数保证能赢应花的钱,则我们依次遍历 1-n作为猜的数,求出其中的最小值即为答案,即最小的最大值问题。

技术分享

Guess Number Higher or Lower II--困惑

标签:time   leetcode   money   而且   eth   get   技术分享   from   区间   

原文地址:http://www.cnblogs.com/jingjingblog/p/6250599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!