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
The minimum path sum from top to bottom is
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];
}
};
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];
}
};
相关文章推荐
- LeetCodeOJ--Reverse Words in a String(python版本)
- LeetCodeOJ_168_Excel Sheet Column Title
- LeetCodeOJ_242_Valid Anagram
- LeetCode#120. Triangle
- Middle-题目60:120. Triangle
- 120. Triangle(dp)
- Leetcode 120. Triangle
- 120. Triangle
- [LeetCode]120. Triangle
- leetcodeOJ 231. Power of Two
- leetcodeOJ 61. Rotate List
- 120. Triangle
- (DP)LeetCode#120. Triangle
- (M)Dynamic Programming:120. Triangle
- LeetCode 120. Triangle
- LeetCode 120. Triangle
- LeetCodeOJ--Remove Duplicates from Sorted Array(c++ && python版本)
- LeetCodeOJ_160_Intersection of Two Linked Lists
- LeetCodeOJ_190_Reverse Bits
- 120. Triangle