给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
说明:
如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
//使用一个一位数组,长度为最后一条边的长度
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int rows = triangle.size();
if(rows == 0){
return 0;
}
int columns = triangle[rows - 1].size();
vector<int> dp(columns, 0);
dp[0] = triangle[0][0];
for(int i = 1; i< rows; i++){
for(int j = triangle[i].size() - 1; j >= 0; j--){
if(j == triangle[i].size() - 1){
dp[j] = dp[j - 1] + triangle[i][j];
}else if(j == 0){
dp[j] = dp[j] + triangle[i][j];
}else{
dp[j] = std::min(dp[j - 1], dp[j]) + triangle[i][j];
}
}
for(int i = 0; i< columns; i++){
cout<< dp[i];
}
cout<< endl;
}
sort(dp.begin(), dp.end());
return dp[0];
}
};
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/69927545/viewspace-2648161/