Source: https://leetcode.com/problems/triangle/
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
思路:DP
第一种是空间复杂度
O
(
n
2
)
O(n^2)
O(n2)的,
d
p
[
i
]
[
j
]
dp[i][j]
dp[i][j]表示
t
r
i
a
n
g
l
e
[
i
]
[
j
]
triangle[i][j]
triangle[i][j]到最后一行路径之和的最小值,那么
d
p
[
i
]
[
j
]
=
min
(
d
p
[
i
+
1
]
[
j
]
,
d
p
[
i
+
1
]
[
j
+
1
]
)
+
t
r
i
a
n
g
l
e
[
i
]
[
j
]
dp[i][j]=\min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j]
dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j],限制范围是
0
≤
i
<
n
−
1
0\leq i<n-1
0≤i<n−1,
0
≤
j
≤
i
0\leq j\leq i
0≤j≤i,对于
i
=
=
n
−
1
i==n-1
i==n−1的,就等于最后一行的triangle值。
第二种是第一种的优化,空间复杂度
O
(
n
)
O(n)
O(n)。上面的式子看出,每次更新只用到下一行的两个数据,所以维护一个一维数组,逐行覆盖就行。
d
p
[
j
]
=
min
(
d
p
[
j
]
,
d
p
[
j
+
1
]
)
+
t
r
i
a
n
g
l
e
[
i
]
[
j
]
dp[j]=\min(dp[j],dp[j+1])+triangle[i][j]
dp[j]=min(dp[j],dp[j+1])+triangle[i][j],
i
i
i控制外层循环,从n-2减到0.
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n=triangle.size();
vector<int> dp(triangle.back());
for(int i=n-2;i>=0;i--){
for(int j=0;j<=i;j++){
dp[j]=min(dp[j],dp[j+1]);
dp[j]+=triangle[i][j];
}
}
return dp[0];
}
};