leetcode---Triangle---动规

来源:互联网 发布:怎么设置淘宝店头页 编辑:程序博客网 时间:2024/04/29 02:28

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
这里写图片描述
The minimum path sum from top to bottom is 11 (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];          memset(dp, 0, sizeof(dp));        if(triangle[0].size() == 0)            return 0;        for(int i=0; i<triangle[n-1].size(); i++)        {            dp[n-1][i] = triangle[n-1][i];         }        for(int j=n-2; j>=0; j--)        {            for(int k=0; k<triangle[j].size(); k++)            {                dp[j][k] =  min(dp[j+1][k] + triangle[j][k], dp[j+1][k+1] + triangle[j][k]);            }        }        return dp[0][0];    }};
0 0
原创粉丝点击