您的位置:首页 > 其它

Leetcode: Triangle

2015-06-07 11:37 495 查看
最近都在复习英语,看见看得头都大了,而且阅读越做分数越低!换个环境,做做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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: