码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Triangle

时间:2015-08-12 19:35:23      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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.

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.

解题思路:

动态规划。用d来记录从根到页的最短路径,i为当前行数。则有

d[j] = d[j-1] + triangle[i][j],j==i时

d[j] = d[0] + triangle[i][0], j==0时

d[j] = min(d[j-1], d[j]) + triangle[i][j],其他。

注意计算d[j]时,会用到上一次的d[j-1],因此可以按d[i..0]的顺序来计算。

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int n = triangle.size();
        if(n==0){
            return 0;
        }
        if(n==1){
            return triangle[0][0];
        }
        int d[n];
        d[0] = triangle[0][0];
        for(int i=1; i<n; i++){
            for(int j=i; j>=0; j--){    //这里从由高到低
                if(j==i){
                    d[j] = d[j-1] + triangle[i][j];
                }else if(j==0){
                    d[j] = d[0] + triangle[i][0];
                }else{
                    d[j] = min(d[j-1], d[j]) + triangle[i][j];
                }
            }
        }
        
        int minPath = d[0];
        for(int i=1; i<n; i++){
            minPath = min(d[i], minPath);
        }
        
        return minPath;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Triangle

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47447585

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!