您的位置:首页 > 其它

leetcode题解-120. Triangle

2017-04-17 11:56 706 查看
题目:

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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: