leetcode---triangle---dp

来源:互联网 发布:linux配置javahome 编辑:程序博客网 时间:2024/06/01 08:43

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 is11(i.e., 2 + 3 + 5 + 1 = 11).

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle)     {        int n = triangle.size();        if(n == 0)            return 0;        int dp[n][n];        dp[0][0] = triangle[0][0];        for(int i=1; i<n; i++)        {            for(int j=0; j<=i; j++)            {                if(j == 0)                    dp[i][j] = dp[i-1][j] + triangle[i][j];                else if(j == i)                    dp[i][j] = dp[i-1][j-1] + triangle[i][j];                else                    dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j];            }        }        int min = dp[n-1][0];        for(int i=1; i<n; i++)            if(dp[n-1][i] < min)                min = dp[n-1][i];        return min;    }};
原创粉丝点击