Leetcode 374 & 375
374 Guess Number Higher or Lower
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 is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
题意分析
374是一道简单题,给出一个数字n,猜1到n中的数字中的一个,通过调用API guess函数来判断你的猜测是比结果大还是小,返回1表示猜得太大,-1反之,0就正确了,通过一个简单的二分查找就可以得出答案,solution里面还有用三分查找,道理一样的。二分的代码如下:
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int low = 1, high = n, mid, res;
while (low <= high) {
mid = low + (high - low) / 2;
res = guess(mid);
if (res == 0)
return mid;
if (res < 0)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
};
375 Guess Number Higher or Lower II
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.
题意分析
这道题就比较难了,题目意思是这样的,同样是猜1到n的一个数字,比如说n=10,结果为8,我猜5,错了,我要给你5块钱,你说猜小了。我再猜9,错了,我给你9块钱,你说猜大了。我再猜8,猜对了。一路下来我要给17块钱,问题就是求解我至少需要多少钱,才能保证我一定能赢?
解题之前先再来思考一下题目的情况,大致就是“要找出最小的最大值”,就是从1到n中,我应该怎么选才能使得我花的钱最少,但是又能保证我赢。比如说n=5,结果为2,如果我一开始猜3,大了,然后我可以选择猜1、2或者4、5,那么这个时候我就应该至少有3 + 4 = 7块钱才能保证我一定能赢,因为如果我只有3 + 2 = 5块钱,并且结果为4的情况下,我第二轮选4或者5都有可能让我输,但是如果我有4,无论我选1、2、4,我都能保证最后我能赢。然后再讨论一开始选择1、2、3、4、5五种情况下的花费最少的情况,就是结果。
想到这里,就可以用分治(动态规划)的方法来做,先选出一个i,然后把一个数组分成i的左边跟右边,找出左边右边的较大者加上i,然后取出1到n中最小的结果的那个i的方案,就是最后的答案,代码如下:
class Solution {
public:
// 数组nums[i][j]表示的是在已经选择了i的前提下,选中最后结果为j的情况所需的总的花费
int getMoneyAmount(int n) {
int **nums = new int*[n + 1];
for (int i = 0; i <= n; i++) {
nums[i] = new int [n + 1];
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
nums[i][j] = 0;
int res = solve(nums, 1, n);
for (int i = 0; i <= n; i++)
delete []nums[i];
delete []nums;
return res;
}
int solve(int** nums, int left, int right) {
// 当左边的边界大于等于右边边界的时候,表明已经到了极限,游戏结束
if (left >= right)
return 0;
// 这里用一个保存的方法,避免重新进入数组的时候重新计算
if (nums[left][right] != 0)
return nums[left][right];
int res = INT_MAX;
int temp;
for (int i = left; i <= right; i++) {
// 考虑最坏的情况
temp = i + max(solve(nums, left, i - 1), solve(nums, i + 1, right));
if (temp < res)
res = temp;
}
// 记得要把数组的值保存
nums[left][right] = res;
return res;
}
};