您的位置:首页 > 编程语言 > C语言/C++

leetcodeOJ 120. Triangle

2017-04-09 21:59 441 查看
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.

思路:对空间复杂度有要求,申请一个n大小的数组,初始化为第n-1行的元素,

本题可用动态规划来解,从下往上处理,第i行第j列元素的值为(min(第i+1行第j列元素,第i+1行第j+1列元素)+  第i行第j列元素)

代码如下:

//动态规划
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
int ans
;
for(int i = 0; i < n; i++){
ans[i] = triangle[n-1][i];//初始化为最后一列
}
for(int i = 0; i < n-1; i++){
for(int j = 0; j < n-1-i; j++){
ans[j] = triangle[n-2-i][j] + min(ans[j], ans[j+1]);
}
}
return ans[0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息