-
Notifications
You must be signed in to change notification settings - Fork 0
/
120_minimumTotal.txt
35 lines (34 loc) · 1.1 KB
/
120_minimumTotal.txt
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
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
//经典动态规划
int n = triangle.size();
vector<vector<int>> dp(n, vector<int>(n));
dp[0][0] = triangle[0][0];
for(int i = 1;i<n;++i){
dp[i][0] = dp[i-1][0] + triangle[i][0];//该行最左侧
for(int j = 1;j < i;++j){
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j];
}
dp[i][i] = dp[i-1][i-1] + triangle[i][i];//该行最右侧
}
return *min_element(dp[n-1].begin(),dp[n-1].end());
}
};
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
//经典动态规划,空间优化
int n = triangle.size();
vector<int> f(n);
f[0] = triangle[0][0];
for (int i = 1; i < n; ++i){
f[i] = f[i - 1] + triangle[i][i];
for (int j = i - 1; j > 0; --j) {
f[j] = min(f[j - 1], f[j]) + triangle[i][j];
}
f[0] += triangle[i][0];
}
return *min_element(f.begin(), f.end());
}
};