Triangle -- Leetcode

来源:互联网 发布:淘宝怎么提升浏览量 编辑:程序博客网 时间:2024/06/06 01:26

12.27 2014

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.

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle) {        int m=triangle.size();        int* sum=new int[m];        for(int i=0;i<m;i++)            sum[i]=0;        for(int i=m-1;i>=0;i--){            int n=triangle[i].size();            for(int j=0;j<n;j++){                if(i==m-1){                    sum[j]=triangle[i][j];                    continue;                }                sum[j]=min(sum[j],sum[j+1])+triangle[i][j];            }        }        return sum[0];    }};

总结:

以后遇到这种需要层层递进判断的题目,可以考虑有DP来做。此题一维DP即可。这道题从下往上比较好,就可以比较轻松的对DP数组sum进行初始化。

0 0
原创粉丝点击