leetcode题解-120. Triangle
2017-04-17 11:56
706 查看
题目:
题目是为了寻找和最小的路径。看到本题我们最先想到的可能是DFS深度遍历方法,遍历每一条路径求出答案即可,但是我们会发现使用DFS会造成很多重复的计算,导致效率低下。所以尝试DP算法,看到本题,我们应当首先考虑使用自上向下还是自下向上的方法。这里我们采用自下向上==基本的思路就是从下向上修改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.
题目是为了寻找和最小的路径。看到本题我们最先想到的可能是DFS深度遍历方法,遍历每一条路径求出答案即可,但是我们会发现使用DFS会造成很多重复的计算,导致效率低下。所以尝试DP算法,看到本题,我们应当首先考虑使用自上向下还是自下向上的方法。这里我们采用自下向上==基本的思路就是从下向上修改triangle的每个元素,将其修改为下面相邻两个数中较小值与该元素的求和,这样就符合题意,到达顶部时的那个元素就是我们想要的答案。代码入下:
public int minimumTotal1(List<List<Integer>> triangle) { for(int i=triangle.size()-2; i>=0; i--) for(int j=0; j<=i; j++) triangle.get(i).set(j, triangle.get(i).get(j)+Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1))); return triangle.get(0).get(0); }
这种方法造成了过多的更新等操作,我们可以尝试者使用额外的空间来保存求和结果,可以大大提升代码效率。如下所示;
public int minimumTotal(List<List<Integer>> triangle) { int row = triangle.size(); int [] res = new int[row+1]; for (int i=row-1; i>=0; i--){ List<Integer> tmp = triangle.get(i); for(int j=0; j<tmp.size(); j++) res[j] = Math.min(res[j], res[j+1]) + tmp.get(j); } return res[0]; }
相关文章推荐
- Leetcode题解 120. Triangle
- [LeetCode]题解(python):125-Valid Palindrome
- [LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
- LeetCode(100)题解--Same Tree
- LeetCode题解——Sudoku Solver
- Leetcode 题解系列(一)
- leetcode 27 题解 翻译 Python版
- LeetCode 104. Maximum Depth of Binary Tree 题解(C++)
- LeetCode题解:Construct the Rectangle
- LeetCode题解:Palindrome Number
- LeetCode 3. Longest Substring Without Repeating Characters 题解——Java
- [Leetcode] 120. Triangle 解题报告
- LeetCode题解:Balanced Binary Tree
- LeetCode题解——7Reverse Integer
- [LeetCode]题解(python):024-Swap Nodes in Pairs
- leetcode题解-126. Word Ladder II
- LeetCode题解-14-Longest Common Prefix
- leetcode题解||Reverse Integer 问题
- Leetcode题解(十七)
- LeetCode题解:Single Number