您的位置:首页 > 其它

120. Triangle

2016-11-19 09:35 369 查看

QUESTION

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.

THINKING

这道题是根据给出的杨辉三角,找到和最小的路径,要求是移动到下一行时,只能是本列或者下一列,这是动态规划的问题。首先建立一个数组,大小为杨辉三角的行数,在遍历每一行的每一列元素时,把找到本列或者前一列最小的数和本元素相加存入的数组中。这里没有采用这种做法的原因是不好实现,所以采用了从下往上的方式。

CODE

public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int[] DP = new int[triangle.size() + 1];
for(int i = triangle.size() - 1;i >= 0;i--){
for(int j =0;j < triangle.get(i).size();j++){
DP[j] = Math.min(DP[j],DP[j + 1]) + triangle.get(i).get(j);
}
}
return DP[0];
}
}


RESULT

time complexity is: O(n^2);space complexity is: O(n);

二刷

还是用动态规划的思路去做,首先建立一个列表,把triangle的第一行放进去,同时在0的位置上加上一个最大值记为curr,然后把第二行的列表取出来记为row,然后更新curr的值。

CODE

public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int min = Integer.MAX_VALUE;
List<Integer> curr = triangle.get(0);
if(triangle.size() == 1)
return curr.get(0);
curr.add(0,Integer.MAX_VALUE);
for(int i = 1;i < triangle.size();i++){
List<Integer> row = triangle.get(i);
for(int j = 0;j < row.size();j++){
if(j == row.size() - 1){
int num =  curr.get(j) + row.get(j);
curr.set(j,num);
}
else{
int num= row.get(j) + Math.min(curr.get(j),curr.get(j + 1));
curr.set(j,num);

}
if(i == triangle.size() - 1)
min = Math.min(curr.get(j),min);
}
curr.add(0,Integer.MAX_VALUE);
}
return min;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: