【一天一道LeetCode】#120. Triangle
2016-07-05 22:21
423 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
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.
(二)解题
题目大意:给定一个三角矩阵,求从上到下的路径中和最小的路径。每次向下走只能从相邻的数走。解题思路:Note中提到空间复杂度要为O
,n为最下面一行数的个数
这种问题一般都会想到动态规划,所以直接往转移方程上想。
记dp[i][j]为(i,j)点到最低端的最小路径和。n为矩阵的深度
则从第n-1行开始,dp[i][j] += min(dp[i+1][j],dp[i+1][j+1]),一路往上计算,最终dp[0][0]即为所求。
于是很快写出代码,10msAC版本。
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { if(triangle.empty()) return 0; vector<vector<int>> dp = triangle; int n = dp.size(); if(n==1) return triangle[0][0];//只有一行的时候直接返回 for(int i = n-2 ; i >=0 ; i--) { for(int j = 0 ; j < dp[i].size();j++) { dp[i][j] += min(dp[i+1][j],dp[i+1][j+1]);//状态转移方程 } } return dp[0][0]; } };
考虑到优化上述代码,使得空间复杂度更低,满足O(n),其实,只用一个一维数组就能解决问题。
下面的代码时优化后的版本,8msAC.
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { if(triangle.empty()) return 0; int n = triangle.size(); vector<int> 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]+min(dp[j],dp[j+1]); } } return dp[0]; } };
相关文章推荐
- Android之使用Http协议实现文件上传功能
- 查看github pages文档的方式
- 使用BAE的基于Web.py的简单博客程序
- 菜鸟说给菜鸟听之Beginning Linux Programming——Chapter1(1)
- sqlserver FOR XML PATH 语句的应用
- 关于jquery中全局函数each使用介绍
- 两分钟学会如何在github托管代码
- set_include_path在win和linux下的区别
- C#利用delegate实现Javascript的each方法
- 简单几行JS Code实现IE邮件转发新浪微博
- js实现新浪微博首页效果
- jquery中map函数与each函数的区别实例介绍
- jQuery.each()用法分享
- 浅析jQuery 遍历函数,javascript中的each遍历
- jquery里的each使用方法详解
- Jquery中find与each方法用法实例
- 浅析Cookie中的Path与domain
- jquery使用each方法遍历json格式数据实例
- jQuery使用each方法与for语句遍历数组示例