LeetCode|Triangle
来源:互联网 发布:类似于yolo的软件 编辑:程序博客网 时间:2024/05/16 14:55
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.
思路:
以层为单位,记录到该层第i个元素的最短距离。
除了每层的第一个和最后一个,其他位置的最短路径都可能从上一层的两个位置过来。
last: ○ ○
\ /
cur: ○
class Solution {public: int minimumTotal(vector<vector<int>>& tri) { int n = tri.size(); if(n == 0) return 0; int last[n]; // store the minimal path of (i-1)-th level int cur[n]; // store the minimal path of (i)-th level last[0] = tri[0][0]; for(int i = 1; i < n; i++){ cur[0] = last[0] + tri[i][0]; // 0-th element for(int j = 1; j < i; j++) {cur[j] = min(last[j-1], last[j]) + tri[i][j];} cur[i] = last[i-1] + tri[i][i];// (i)-th element for(int j = 0; j <= i; j++) last[j] = cur[j]; // update last } int res = last[0]; // if n = 1, cur[0] is not exist for(int i = 1; i < n; i++) if(res > last[i]) res = last[i]; return res; }};
这是我大二算法课的机考题,那个学期课程紧没有好好学算法,所以没有想到解法。
0 0
- LeetCode : Triangle
- [LeetCode] Triangle
- [Leetcode] Triangle
- [LeetCode] Triangle
- 【leetcode】Triangle
- LeetCode - Triangle
- [LeetCode]Triangle
- [Leetcode]Triangle
- [leetcode]Triangle
- Leetcode: Triangle
- [LeetCode] Triangle
- LeetCode-Triangle
- [leetcode] Triangle
- [LeetCode] Triangle
- LeetCode - Triangle
- 【Leetcode】Triangle
- LeetCode | Triangle
- [leetcode]Triangle
- Java基础部分
- Parallelogram Counting(POJ1971)
- python本地文件
- Eclipse启动报错”java was started but returned exit code=13”
- 字典树,HDU 1251 hash前缀
- LeetCode|Triangle
- 无人机的现状与展望
- 各类总线传输速率
- 如何修改linux 的SSH的默认端口号?
- C++string类用法总结
- Educational Codeforces Round 12 E. Beautiful Subarrays【字典树】
- Irrlicht学习笔记(3)--CustomSceneNode
- PHP经典算法百钱买小鸡
- LeetCode 340. Longest Substring with At Most K Distinct Characters(最长字串)