[leetcode.com]算法题目 - Triangle

时间:2023-03-09 04:40:20
[leetcode.com]算法题目 - 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.

 class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function }
};

答题模板

思路:假设三角形共有n行,题目中看出第i行共有i个元素。从top到bottom,我们只考虑minimum path的最后一步是停在了这n个元素的哪一个上面。用数组min_sum(k)表示最后一行到达第k个元素的最小路径(min_sum总长度为n),然后找出min_sum(k)中最小的元素即可。注意一下自上而下递推min_sum时候的递推公式,代码如下:

 class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function int n = triangle.size();
if ( == n) return ;
if ( == n) return triangle[][]; int *min_sum = new int[n];
for(int i=; i<n;i++)
min_sum[i] = ; min_sum[]=triangle[][];
for(int i=;i<n;i++){
for(int j=triangle[i].size()-; j>=;j--){
if (==j){
min_sum[j] += triangle[i][];
}else if (triangle[i].size()-==j){
min_sum[j] = min_sum[j-]+triangle[i][j];
}else{
min_sum[j] = min(min_sum[j-], min_sum[j])+triangle[i][j];
}
}
} int minTotal = min_sum[];
for(int i=;i<n;i++){
minTotal = min(minTotal, min_sum[i]);
} delete[] min_sum;
return minTotal;
} int min(int a, int b){
return (a>b?b:a);
}
};

Answer

注意:一开始的时候内部j那个循环是正着写,后来发现这样有个问题,就是有可能会使用已经变动的过的值去更新下一列。