374 Guess Size
Topic Description: We're playing a guessing game. Rules of the game are as follows:
I n select a number from 1 to. I guess you need to choose which number. Every time you guess wrong, I'll tell you this figure is big or small. You call a pre-defined interfaces guess (int num), it will return three possible outcomes (-1, 1 or 0): -1: I figure is relatively small; 1: I figure larger; 0: Congratulations! you guessed right!
Ideas: half guessing.
// 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);
int ABC(int n);
class Solution {
public:
int guessNumber(int n) {
long long low = 1, high = n, mid = 0;
int ans = 0;
while(low <= high) {
mid = (low + high) / 2;
if(guess(mid) <= 0) {
ans = mid;
high = mid - 1;
}
else
low = mid + 1;
}
return ans;
}
};
375 Guess Size 2
Topic Description: We're playing a guessing game, rules of the game are as follows:
I select a number from 1 to n, you guess what number I chose. Every time you guess wrong, I will tell you, I chose numbers than your big or small. However, when you guess wrong as digital x and when you need to pay x amount of cash. I guess until you choose the numbers, you win the game be considered.
Given n ≥ 1, at least you need to calculate how much cash to make sure you can win this game.
Ideas: dynamic programming range.
Topic understand: give you a n, he may have the actual numbers (ie I choose the number) is any 1-n one (denoted by i), for each i, there are many guess law, there is an answer spending is the smallest. We have a minimum cost for each i, then the answer is the maximum of all i corresponding minimum cost.
class Solution {
public:
int getMoneyAmount(int n) {
vector<vector<int>> dp(n+2, vector<int>(n+2, 100000000));
for(int i = 1; i <= n; i++) {
for(int j = 0; j <= i; j++){
dp[i][j] = 0;
}
}
for(int len = 2; len <= n; len++) {
for(int L = 1; L + len - 1 <= n; L++) {
int R = L + len - 1;
for(int mid = L; mid <= R; mid++)
dp[L][R] = min(dp[L][R], max(dp[L][mid - 1], dp[mid + 1][R]) + mid);
}
}
return dp[1][n];
}
};