Leetcode 120 Triangle

来源:互联网 发布:单片机 红外发射 编辑:程序博客网 时间:2024/05/16 15:18

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.

数塔DP,没什么好说的。

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {        vector<vector<int>> dp=triangle;        for(int i=1;i<dp.size();i++)        {            for(int j=0;j<dp[i].size();j++)            {                vector<int> temp;                if(j!=0) temp.push_back(dp[i-1][j-1]);                if(j!=dp[i].size()-1) temp.push_back(dp[i-1][j]);                sort(temp.begin(),temp.end());                dp[i][j]=temp[0]+dp[i][j];            }        }        sort(dp[dp.size()-1].begin(),dp[dp.size()-1].end());        return dp[dp.size()-1][0];    }};


1 0