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 int len = triangle.size();
7 int *a;
8 a = new int[len];
9 a[0] = 0;
10 int i,j;
11 for(i = 0; i < len;i++)
12 {
13
14 for(j = i;j >= 0;j--)
15 {
16 if(j == 0)
17 a[j] = triangle.at(i).at(j) + a[j];
18 else if(j == i)
19 a[j] = triangle.at(i).at(j) + a[j - 1];
20 else
21 {
22 int k = triangle.at(i).at(j);
23 k += (a[j]>a[j-1])?a[j-1]:a[j];
24 a[j] = k;
25 }
26 }
27 }
28 int min = 9999999;
29 for(int i = 0; i <len;i++)
30 min = (min > a[i])?a[i]:min;
31 return min;
32 }
33 };