【一天一道LeetCode】#120. Triangle
2016-07-05 22:21
309 查看
一天一道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.
(二)解题
题目大意:给定一个三角矩阵,求从上到下的路径中和最小的路径。每次向下走只能从相邻的数走。解题思路: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]; } };
相关文章推荐
- Maintaining Your Signing Identities and Certificates 维护你的签名标识和证书
- 员工转正与导师
- icomoon图标的使用
- The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path 解决方法
- [Java学习日志]关于字符串的二三事
- centos7下使用yum安装mysql数据库以及设置远程访问
- How do I add elements to a Scala List?
- geeksforgeeks@ Find sum of different corresponding bits for all pairs (Bit manipulation)
- spring学习(三)—AOP
- Tomcat漏洞
- 《leetCode》: Maximal Square
- android中的资源文件
- hdu:1556 Just a Hook
- 在android studio中新建android gradle project的时候connect refused:connect或者卡在building project...或Refreshing
- leetcode:Rotate List
- Java基础知识(一)
- centos7安装zabbix3.0.3
- tomcat 配置虚拟站点
- Cache应用中的服务过载案例研究
- Ubuntu入门学习笔记(1)