首页 > 其他 > 详细

LeetCode之“动态规划”:Triangle

时间:2015-06-09 13:24:32      阅读:148      评论:0      收藏:0      [点我收藏+]

  题目链接

  题目要求: 

  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

1 [
2      [2],
3     [3,4],
4    [6,5,7],
5   [4,1,8,3]
6 ]

  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         int rows = triangle.size();
 5         if(rows == 0)
 6             return 0;
 7         
 8         int * dp = new int[rows];
 9         int szOfLastRow = triangle[rows - 1].size();
10         for(int i = 0; i < szOfLastRow; i++)
11             dp[i] = triangle[rows - 1][i];
12         
13         for(int i = rows - 2; i > -1; i--)
14         {
15             int cols = triangle[i].size();
16             for(int j = 0; j < cols; j++)
17                 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
18         }
19         
20         return dp[0];
21     }
22 };
View Code

  这个程序中最核心的地方在:

dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);

  可以用图表示如下:

  技术分享

  其中一个例子就是:

  技术分享

  需要注意的就是这个例子中只改变的是dp[0],dp[1]并没有改变。

 

LeetCode之“动态规划”:Triangle

原文:http://www.cnblogs.com/xiehongfeng100/p/4562901.html

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