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)刚开始的想法都用到了n平方的空间,实际上可以把每行n个设置为dp数组,表示改点到根节点的最小和,我的方法由于从上到下需要判断额外边界,实际上从下到上更简单更一般性,而且可以不用额外数组最后的根节点即为最小值
代码:
class Solution {
public:
int minimumTotal(vector<vector<int>> &triangle) {
int n=triangle.size();
if(n==0) return 0;
vector<int> dp(n,INT_MAX);
dp[0]=triangle[0][0];
int ans=INT_MAX;
for(int i=1;i<n;i++){
for(int j=triangle[i].size()-1;j>=0;j--){
if(j!=0) dp[j]=min(dp[j],dp[j-1])+triangle[i][j];
else dp[j]=dp[j]+triangle[i][j];
if(i==n-1){ans=min(ans,dp[j]);}
}
}
if(n==1) return triangle[0][0];
return ans;
}
};
优化:
class Solution {
public:
int minimumTotal(vector<vector<int>> &triangle) {
vector<int> dp=triangle[triangle.size()-1];
for(int i=triangle.size()-2;i>=0;i--){
for(int j=0;j<triangle[i].size();j++){
dp[j]=min(dp[j],dp[j+1])+triangle[i][j];
}
}
return dp[0];
}
};
最优化:
class Solution {
public:
int minimumTotal(vector<vector<int>> &triangle) {
for(int i=triangle.size()-2;i>=0;i--){
for(int j=0;j<triangle[i].size();j++){
triangle[i][j]=min(triangle[i+1][j],triangle[i+1][j+1])+triangle[i][j];
}
}
return triangle[0][0];
}
};