LeetCode OJ - Triangle
来源:互联网 发布:照片冲印软件 编辑:程序博客网 时间:2024/05/21 17:08
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.
分析:DFS估计就会超时、根据Node采用record[n]来记录每到一层,某个位置的最小路径。
class Solution { int ret = INT_MAX;public: int minimumTotal(vector<vector<int> > &triangle) { if(triangle.size() == 0) return 0; DFS(triangle, 0, 0, 0); return ret; } void DFS(vector<vector<int> > &triangle, int level, int i, int item) { item += triangle[level][i]; if(level == triangle.size() - 1) { ret = min(ret, item); return ; } DFS(triangle, level + 1, i, item); DFS(triangle, level + 1, i + 1, item); }};从底至上来不断获取最大值,还是用record[n]来记录,时间复杂度为O(n^2)
class Solution { int ret = INT_MAX;public: int minimumTotal(vector<vector<int> > &triangle) { int len = triangle.size(); if(len == 0) return 0; int *record = new int[len]; for(int i = 0; i < len; i++) { record[i] = triangle[len-1][i]; } for(int i = len - 2; i >= 0; i--) { for(int j = 0; j < triangle[i].size(); j++) { int cur = triangle[i][j]; int left = cur + record[j]; int right = cur + record[j+1]; record[j] = min(left, right); } } return record[0]; }};
0 0
- LeetCode OJ:Triangle
- LeetCode OJ - Triangle
- LeetCode OJ Triangle
- <LeetCode OJ> 120. Triangle
- [LeetCode OJ]Triangle
- LeetCode OJ:Pascal's Triangle
- LeetCode OJ - Pascal's Triangle
- LeetCode OJ Pascal's Triangle
- LeetCode OJ:Pascal's Triangle II
- LeetCode OJ - Pascal's Triangle II
- LeetCode OJ 之 Triangle (三角形)
- LeetCode OJ Pascal's Triangle II
- LeetCode OJ 之 Pascal's Triangle(杨辉三角)
- http://oj.leetcode.com/problems/pascals-triangle-ii/
- LeetCode OJ 系列之118 Pascal's Triangle --Python
- <LeetCode OJ> 118 / 119 Pascal's Triangle(I / II)
- LeetCode : Triangle
- [LeetCode] Triangle
- LeetCode OJ - Best Time to Buy and Sell Stock II
- LeetCode :: Reorder List
- put your hands up
- iOS之捕获异常
- OpenNI2+VS2012(64bit)环境配置
- LeetCode OJ - Triangle
- 十进制转换成其他进制数
- C++ string 的写时复制
- LeetCode OJ - Largest Rectangle in Histogram (3*)
- sharepoint 2013 部署解决方案 此功能已在此服务器场中安装 ID 为 guid 的功能。请使用强制属性显式地重新安装
- PHP __call
- LeetCode OJ - Swap Nodes in Pairs
- 如何在mysql中存取utf8mb4编码的字符
- MyEclipse中设置智能提示