120. Triangle

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值