首页 > 其他 > 详细

Dynamic Programming

时间:2017-03-01 00:20:50      阅读:246      评论:0      收藏:0      [点我收藏+]

1、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.

 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

 

Dynamic Programming

原文:http://www.cnblogs.com/yaowenhui/p/6481576.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!