今天闲来无事,做了三道leetcode水题,怒更两发博客,也挺不错。今天更新的两篇都是dp解法的简单题。
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 n = triangle.size();
        if (n==0) return 0;
        if (n==1) return triangle[0][0];
        int dp[n+1];
        int Min = INT_MAX;
        for (int i=0;i<n+1;i++)
            dp[i]=INT_MAX;
        dp[1] = triangle[0][0];
        for (int i=1;i<n;i++){
            for (int j=i+1;j>0;j--){
                dp[j]=min(dp[j-1],dp[j])+triangle[i][j-1];
                if (i==n-1&&dp[j]<Min){
                    Min = dp[j];
                }
            }
        }
        return Min;
    }
};版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/monkeyduck/article/details/47665755