Dynamic Programming
1、Triangle
[2017/3/1] 第一遍 NO-BUG-FREE
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Notice
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.
Example
View Code
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).
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 /** 4 * @param triangle: a list of lists of integers. 5 * @return: An integer, minimum path sum. 6 */ 7 int minimumTotal(vector<vector<int> > &triangle) { 8 // write your code here 9 if (triangle.size() == 0) { 10 return -1; 11 } 12 if (triangle[0].size() == 0) { 13 return -1; 14 } 15 int n = triangle.size(); 16 vector<vector<int> > res(n, vector<int>(n, 0)); 17 for (int i = 0; i < n; i++) { 18 res[n - 1][i] = triangle[n - 1][i]; 19 } 20 for (int i = n - 2; i >= 0; i--) { 21 for (int j = 0; j <= i; j++) { 22 res[i][j] = min(res[i + 1][j], res[i + 1][j + 1]) + triangle[i][j]; 23 } 24 } 25 return res[0][0]; 26 } 27 };