## [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.

1 class Solution {
2 public:
3     int minimumTotal(vector<vector<int> > &triangle) {
4         // Start typing your C/C++ solution below
5         // DO NOT write int main() function
6
7     }
8 };

 1 class Solution {
2 public:
3     int minimumTotal(vector<vector<int> > &triangle) {
4         // Start typing your C/C++ solution below
5         // DO NOT write int main() function
6
7
8         int n = triangle.size();
9         if (0 == n) return 0;
10         if (1 == n) return triangle[0][0];
11
12         int *min_sum = new int[n];
13         for(int i=0; i<n;i++)
14             min_sum[i] = 0;
15
16         min_sum[0]=triangle[0][0];
17         for(int i=1;i<n;i++){
18             for(int j=triangle[i].size()-1; j>=0;j--){
19                 if (0==j){
20                     min_sum[j] += triangle[i][0];
21                 }else if (triangle[i].size()-1==j){
22                     min_sum[j] = min_sum[j-1]+triangle[i][j];
23                 }else{
24                     min_sum[j] = min(min_sum[j-1], min_sum[j])+triangle[i][j];
25                 }
26             }
27         }
28
29         int minTotal = min_sum[0];
30         for(int i=1;i<n;i++){
31             minTotal = min(minTotal, min_sum[i]);
32         }
33
34         delete[] min_sum;
35         return minTotal;
36     }
37
38     int min(int a, int b){
39         return (a>b?b:a);
40     }
41 };