LeetCode:Triangle

来源:互联网 发布:javascript字符串反转 编辑:程序博客网 时间:2024/04/29 19:36

         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 onlyO(n) extra space, wheren is the total number of


rows in the triangle.


解题思路:

       首先dp是很容易想到的,用dp[i][j]表示到第i层j列的最小值,那么状态转移为:


dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])+triangle[i][j] ( 0 < j < triangle[i].size() - 1).由于状态转移只与i和i-1


行有关,所以用滚动数组能将其内存优化为O(n)(此处有常系数2).关于内存的优化,其实是可以做


到严格的O(n)的,我们通过反向更新即可实现.


解题代码:

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle)     {        const int n = triangle.size();        int dp[n];        dp[0] = triangle[0][0];        for (int i = 1; i < n; ++i)        {            for (int j = triangle[i].size() - 1; j >= 0 ; --j)            {                if (j == triangle[i].size() - 1 || !j)                    dp[j] = (!j ? dp[0] : dp[j-1]) + triangle[i][j];                else                    dp[j] = min(dp[j],dp[j-1]) + triangle[i][j];            }        }        return *min_element(dp,dp+n);    }};


更简单的代码:

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle)     {        const int n = triangle.size();        int dp[n];        for (int i = n -1; i >= 0; --i)            dp[i] = triangle[n-1][i];        for (int i = n -2; i >= 0; --i)            for (int j = 0; j < triangle[i].size(); ++j)                dp[j] = min(dp[j],dp[j+1]) + triangle[i][j];        return dp[0];    }};


0 0