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

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).

 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 };
View Code

 

posted @ 2017-02-28 23:12  药小药  阅读(96)  评论(0编辑  收藏  举报