-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathGuess_Number_Higher_or_Lower_II.cpp
43 lines (40 loc) · 1.35 KB
/
Guess_Number_Higher_or_Lower_II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
int getMoneyAmountDp(int left, int right, vector<vector<int>>& dp) {
if(left >= right) {
return 0;
}
int& ret = dp[left][right];
if(ret != INT_MAX) return ret;
for(int x = left; x <= right; ++x) {
ret = min(ret, x + max(getMoneyAmountDp(left, x - 1, dp), getMoneyAmountDp(x + 1, right, dp)));
}
return ret;
}
public:
int getMoneyAmount(int n) {
// bottom-up
vector<vector<int>> dp(n + 1, vector<int>(n + 1, INT_MAX));
for(int i = 0; i <= n; ++i) {
dp[i][i] = 0;
}
for(int len = 2; len <= n; ++len) {
for(int left = 1; left + len - 1 <= n; ++left) {
int right = left + len - 1;
for(int x = left; x <= right; ++x) {
int lhs = 0, rhs = 0;
if(x > left) {
lhs = dp[left][x - 1];
}
if(x < right) {
rhs = dp[x + 1][right];
}
dp[left][right] = min(dp[left][right], x + max(lhs, rhs));
}
}
}
return dp[1][n];
// top-down
// vector<vector<int>> dp(n + 1, vector<int>(n + 1, INT_MAX));
// return getMoneyAmountDp(1, n, dp);
}
};