[leetcode] Triangle

来源:互联网 发布:java的socket如何部署 编辑:程序博客网 时间:2024/04/28 09:53

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) {        vector<vector<int> > sum;        int row=triangle.size();        if(row==0) return 0;        if(row==1) return triangle[0][0];        vector<int> temp;        temp.push_back(triangle[0][0]);        sum.push_back(temp);        for(int i=1;i<row;i++){            temp.clear();            for(int j=0;j<=i;j++){                if(triangle[i][j]+(j<1?sum[i-1][0]:sum[i-1][j-1])<=triangle[i][j]+(j>i-1?sum[i-1][j-1]:sum[i-1][j])) temp.push_back(triangle[i][j]+(j<1?sum[i-1][0]:sum[i-1][j-1]));                else temp.push_back(triangle[i][j]+(j>i-1?sum[i-1][j-1]:sum[i-1][j]));            }            sum.push_back(temp);        }        int len=sum.size(),min=1000000;        int col=sum[len-1].size();        for(int i=0;i<col;i++){            if(sum[len-1][i]<min) min=sum[len-1][i];        }        return min;    }};


0 0
原创粉丝点击