算法作业_27(2017.6.8第十六周)

来源:互联网 发布:python count函数 编辑:程序博客网 时间:2024/06/04 19:16

120. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjachttp://write.blog.csdn.net/posteditent 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[i][j] = min(dp[i+1][j] + dp[i+1][j+1]) +dp[i][j]。dp[0][0]就是答案,代码如下:

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


 

120. Triangle

原创粉丝点击