[LeetCode]-Triangle 求三角形中从顶到底最短距离

来源:互联网 发布:淘宝一键抢拍神器 编辑:程序博客网 时间:2024/05/18 13:30

Triangle


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


分析:可以将问题分解考虑,从低至顶的分析方法。

      设状态f[i][j],表示点(i,j)到顶部的距离,则f[i][j]=min(f[i-1][j-1],f[i-1][j])+(i,j),当然最左和最右端的计算方式稍有变化。最后找出最小值即可。

采用滚动数组的方式,由于下层只和上层有关系,所以只需要记录上层的信息即可,这样就把O(n^2)的空间复杂度压缩成了O(n)。
class Solution {public:    int minimumTotal(vector<vector<int> > &triangle) {        int n=triangle.size();        vector<int> f(n);                f[0]=triangle[0][0];        for(int i=1;i<n;i++){            for(int j=triangle[i].size()-1;j>=0;j--){                int mn;                if(j==0){                    mn=f[j];                }                if(j==i){                    mn=f[j-1];                }                else{                    mn=min(f[j-1],f[j]);                }                f[j]=mn+triangle[i][j];            }        }                int min_sum=f[0];        for(int i=1;i<n;i++)            if(min_sum>f[i])min_sum=f[i];        return min_sum;    }};


 

0 0
原创粉丝点击