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.
题目理解:
这个题目可以用DFS的思想来进行求解,可以使用递归或者DP算法,递归算法时间复杂度太长,我们使用动态规划算法,我一开始使用的自上而下的DP算法,公式为:result[i][j] = min(result[i-1][j-1], result[i-1][j]) + triangle[i][j] ,代码如下所示:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size()==1){
return triangle[0][0];
}
int num = triangle.size();
vector<vector<int>> result(num);
for(int i=0;i<num;++i){
result[i].resize(i+1);
}
// result of first line
result[0][0] = triangle[0][0];
// result of other lines
for(int i=1; i<num; ++i){
for(int j=0; j<=i;++j){
if(j==0)
result[i][j] = triangle[i][j] + result[i-1][j] ;
else if(j==i)
result[i][j] = triangle[i][j] + result[i-1][j-1] ;
else
result[i][j] = min(result[i-1][j-1], result[i-1][j]) + triangle[i][j];
}
}
return *min_element(result[num-1].begin(), result[num-1].end());
}
};
算法的时间复杂度为O(N*N), 空间复杂度也为O(N*N), N表示为三角形的层数,但是题目要求的是空间复杂度为O(N), 这对一个刚刚学习DP算法的同学思考来说有些困难,我们可以换一种思维方式来思考,我们知道第i层的每一个值,在经过第i+1层时有两条路径选择,逆向思维就是第i+1层的某一条路径可能是由第i层的两条路径中的其中一条决定。这样我们可以使用自下而上的DP算法来完成也就是:
result[k][i] = min( result[k+1][i], result[k+1][i+1]) + triangle[k][i];
这样操作我们空间复杂度任然是O(N*N),但是自下而上DP可以帮助我们进行优化,我们这里使用滚动数组来压缩空间。代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
// from bottom to top
int num = triangle.size();
vector<int> result = triangle[num-1];
for(int i= num-2;i>=0; --i){
for(int j =0; j<=i; ++j){
result[j] = min(result[j], result[j+1]) + triangle[i][j];
}
}
return result[0];
}
};