设为首页 加入收藏

TOP

leetcode - Triangle
2015-07-20 17:34:26 来源: 作者: 【 】 浏览:2
Tags:leetcode Triangle

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来解决,更好的办法是从后向前计算,这样就可以使用一维数组空间的来解决,符合题目的意思
//那么,动态转移方程为,dp[j] = triangle[i][j] + min(dp[j],dp[j+1])
class Solution {
public:
    int minimumTotal(std::vector
  
    > &triangle) {
		int n = triangle.size();
		if(n < 1) return 0;
		std::vector
   
     dp(triangle[n-1]); for(int i = n - 2; i >= 0; i--) { for(int j = 0; j < triangle[i].size(); j++) { dp[j] = triangle[i][j] + std::min(dp[j],dp[j+1]); } } return dp[0]; } };
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj 2192 zipper 下一篇POJ 2482――Stars in Your Windo..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)