LeetCode -- 120. Triangle

来源:互联网 发布:sql是一种什么语言 编辑:程序博客网 时间:2024/06/14 09:40

题目:

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.


思路:
这道题有些难度,之前第一想法用从上到下的方法寻找最短路径,但是有点傻逼,用了贪心的思想,结果当然不对,没有AC;转念一想,这TM是DP啊,于是又是一顿写,还是不对,边界处理比较麻烦。参考了大佬的想法,从下往上计算路径,一次就AC了,思路很重要,事半功倍~

sz=triangle.size();
初始状态:

d[sz1][i]=triangle[sz1][i],0isz1;

状态转移方程:
d[i][j]=min(d[i+1][j],d[i+1][j+1])+triangle[i][j],0jisz2;

d[0][0]即为最短路径。


C++代码如下:

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