Triangle

来源:互联网 发布:剑三淘宝代练 编辑:程序博客网 时间:2024/05/24 01:46

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 i,j,min,minr;        int n = triangle.size();        if(n==1) return triangle[0][0];        for(i=1;i<n;i++){            for(j=0;j<=i;j++){                if(j!=0 && j!=i){                    minr=(triangle[i-1][j]<triangle[i-1][j-1])?triangle[i-1][j]:triangle[i-1][j-1];                    triangle[i][j]=minr+triangle[i][j];                }                else if(j==0) triangle[i][j]=triangle[i-1][j]+triangle[i][j];                else if(j==i) triangle[i][j]=triangle[i-1][j-1]+triangle[i][j];            }        }        min=triangle[n-1][0];        for(i=1;i<n;i++){              if(triangle[n-1][i]<min) min=triangle[n-1][i];        }          return min;    }};


0 0
原创粉丝点击