Leetcode: Triangle

近期都在复习英语。看见看得头都大了,并且阅读越做分数越低!换个环境,做做Leetcode试题!

题目:

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.

一道动态规划问题。在《动态规划:数塔问题》一文中已经具体描写叙述过这个问题(一个是求最大值,一个是求最小值)。有兴趣的能够參考这篇文章。

只是当时使用的是一个二维的数组,如今使用一个一维的数组对代码进行优化。

动态规划的递推公式为:dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j]

以下给出C++參考代码:

class Solution
{
public:
    int minimumTotal(vector<vector<int> > &triangle)
    {
        int row = triangle.size();
        if (row == 0) return 0;
        vector<int> dp(row); // 初始化dp容大小为triangle最后一行数据的个数
        for (size_t i = 0; i < row; ++i)
        {
            dp[i] = triangle[row - 1][i]; // dp初始化为triangle的最后一行
        }
        // 动态规划
        for (size_t i = row - 1; i > 0; --i)
        {
            for (size_t j = 0; j < triangle[i].size() - 1; ++j)
            {
                dp[j] = min(dp[j], dp[j + 1]) + triangle[i - 1][j];
            }
        }
        return dp[0];
    }
};


posted @ 2017-06-27 19:33  yfceshi  阅读(131)  评论(0编辑  收藏  举报