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
The minimum path sum from top to bottom is
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];
}
};
题目:
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];
}
};
相关文章推荐
- 解决Qt5.2及以上版本无法连接64位mysql问题
- 51单片机汇编实现冒泡排序
- USACO 2.2 Party Lamps 派对灯 (lamps)
- 静态类
- Tiny4412-LED小灯裸机程序
- 【Treap】[BZOJ 3224]Tyvj 1728 普通平衡树
- BZOJ 1652: [Usaco2006 Feb]Treats for the Cows( dp )
- Java 设计模式
- Python标准库:内置函数type(object)
- 战斗进行时
- [Event] Linux con Japan 2015
- [UVA12538]Version Controlled IDE && 可持久化treap
- Python标准库:内置函数type(object)
- 读书笔记之《程序员必读的职业规划书》
- 6.1.1.2 属性类型之访问器属性
- ASP.NET完整打包卸载更新攻略(By Installshield 2010)
- Spring实战3-Spring之旅
- 当执行游戏0xc000007b错误的解决方法
- CMD常用命令
- [镜像制作]VMWare搭建Openstack——guestfish命令修改虚拟机镜像