[Leetcode 65] 120 Triangle
2013-07-16 01:25
281 查看
Problem:
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
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.
Analysis:
Basically, this is a simple dynamic programming problem. Start from the first level, at level i, computing the possible min length of each position at level i give the i-1 level. And after computing the last level, use find_min funnction to get the minimum value of the path. Besides, this solution is an online version. It can always give the current solution.
This time complexity is O(n) and the space complecity is O(n).
Code:
View Code
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.
Analysis:
Basically, this is a simple dynamic programming problem. Start from the first level, at level i, computing the possible min length of each position at level i give the i-1 level. And after computing the last level, use find_min funnction to get the minimum value of the path. Besides, this solution is an online version. It can always give the current solution.
This time complexity is O(n) and the space complecity is O(n).
Code:
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { // Start typing your C/C++ solution below // DO NOT write int main() function for (int i=1; i<triangle.size(); i++) { for (int j=0; j<i+1; j++) { if (j == 0) //first in a row triangle[i][0] += triangle[i-1][0]; else if (j == i) //last in a row triangle[i][i] += triangle[i-1][i-1]; else // two choice & get smaller triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]); } } return find_min(triangle[triangle.size()-1]); } int min(int a, int b) { return (a<b)? a : b; } int find_min(vector<int> v) { int min = v[0]; for (int i=1; i<v.size(); i++) { if (v[i] < min) min = v[i]; } return min; }
View Code
相关文章推荐
- [LeetCode 120] - 三角形(Triangle)
- LeetCode 62/63/120/64 Unique PathsI/II Triangle/Min sum Path/Rectangle Area--DP
- LeetCode 120: Triangle
- Leetcode[120]-Triangle
- [Leetcode 120, Medium] Triangle
- Java for LeetCode 120 Triangle
- Leetcode 120 Triangle
- Leetcode 120 Triangle
- LeetCode 120 Triangle
- leetcode120 triangle
- LeetCode 120 Triangle
- LeetCode120 Triangle
- LeetCode 120 Triangle
- leetcode[120] Triangle
- LeetCode 120 : Triangle
- 【LeetCode-面试算法经典-Java实现】【120-Triangle(三角形)】
- leetcode 120 Triangle
- LeetCode(120) Triangle
- [leetcode] 120 Triangle
- [leetcode 120] Triangle