Triangle

Description:

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.

Code:

 1   int minimumTotal(vector<vector<int> > &triangle) {
 2         //注意三角形的存储顺序,顶端是第一行数据
 3         if (triangle.empty())
 4             return 0;
 5         int row = triangle.size();
 6         
 7         vector<int>nextRow(triangle[row-1]);
 8         vector<int>currentRow;
 9         for (int i = row-2; i >= 0; --i)
10         {
11             int col = triangle[i].size();
12             currentRow = triangle[i];
13             for (int j = 0; j < col; ++j)
14             {
15                 currentRow[j] += min(nextRow[j], nextRow[j+1]);
16             }
17             nextRow = currentRow;
18         }
19         return nextRow[0];
20     }
原文地址:https://www.cnblogs.com/happygirl-zjj/p/4590698.html