码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Triangle

时间:2014-06-27 16:29:58      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

         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是非常easy想到的,用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];
    }
};


LeetCode:Triangle,布布扣,bubuko.com

LeetCode:Triangle

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/mfrbuaa/p/3810000.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!