区间型动态规划题目解析
for (int len = 2; len < n; len++){
for (int i = 0; i < n - len; i++){
int j = i + len;
for (int k = i + 1; k < j; k++){
dp[i][j] = temp + max/min(dp[i+1][j], dp[i][j-1]);
}
}
}
2.题目分析
375. 猜数字大小 II
int getCost(int low, int high){
int res = 0;
int minCost = 65535;
if (low >= high){
return res;
}
for (int i = (low + high) / 2; i <= high; i++){
// 取最大值——最坏情况都能赢,才是确保能够赢
res = i + max(getCost(low, i - 1), getCost(i + 1, high));
minCost = min(minCost, res);
}
return minCost;
}
int getMoneyAmount(int n) {
return getCost(1, n);
}
int getMoneyAmount(int n) {
if (n <= 3){
return n - 1;
}
vector<vector<int>>dp(n + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= n; i++){
dp[i][i] = 0;
}
for (int len = 2; len <= n; len++){
for (int i = 1; i <= n - len + 1; i++){
int minCost = 65535;
int j = i + len - 1;
for (int k = i; k<j; k++){
minCost = min(minCost, k + max(dp[i][k - 1], dp[k + 1][j]));
}
dp[i][j] = minCost;
}
}
return dp[1][n];
}
312. 戳气球
int maxCoins(vector<int>& nums) {
// 一前一尾插入1,不影响结果
nums.insert(nums.begin(), 1);
nums.push_back(1);
int n = nums.size();
vector<vector<int>>dp(n, vector<int>(n));
for (int len = 2; len < n; len++){
for (int i = 0; i<n - len; i++){
int j = i + len;
for (int k = i + 1; k<j; k++){
dp[i][j] = max(dp[i][j], nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j]);
}
}
}
return dp[0][n - 1];
}