CoolSummer

数据可视化

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

二、思路

采用dp动态规划算法,其中:

vector<int> vec = triangle.back();
返回二维数组的最后一行元素的引用。整个算法的递归式为:

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

三、代码

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if(triangle.empty() || triangle[0].empty()) return 0;
        vector<int> vec = triangle.back();
        for(int i = triangle.size() - 2; i >= 0 ;--i){
            for(int j = 0; j < triangle[i].size();++j){
                vec[j] = triangle[i][j] + min(vec[j],vec[j+1]);
            }
        }
        return vec[0];
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014744118/article/details/52357355
个人分类: LeetCode
上一篇Binary Tree Postorder Traversal
下一篇Construct Binary Tree from Preorder and Inorder Traversal
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭