triangle

容易 数字三角形
26%
通过

给定一个数字三角形,找到从顶部到底部的最小路径和。每一步可以移动到下面一行的相邻数字上。

您在真实的面试中是否遇到过这个题? 
Yes
样例

比如,给出下列数字三角形:

[

     [2],

    [3,4],

   [6,5,7],

  [4,1,8,3]

]

从顶到底部的最小路径和为11 ( 2 + 3 + 5 + 1 = 11)。

注意

如果你只用额外空间复杂度O(n)的条件下完成可以获得加分,其中n是数字三角形的总行数。

public class Solution {
    //Memorize Search
    private int n;
    private int [][] sum;
    private ArrayList<ArrayList<Integer>> triangle;
    
    private int search(int x, int y){
        if(x >= n){
            return 0;
        }
        //防止内存溢出
        //有值的sum[i][j]就不再继续递归了,而是直接返回值
        if(sum[x][y] != Integer.MAX_VALUE){
            return sum[x][y];
        }
        sum[x][y] = Math.min(search(x+1,y),search(x+1,y+1)) + triangle.get(x).get(y);
        return sum[x][y];
    }
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
          
        this.n = triangle.size();
        this.sum = new int[n][n];
        this.triangle = triangle;
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j< n; j++){
                sum[i][j] = Integer.MAX_VALUE;                              
            }
        }
        return search(0,0);
    }
}
// 动态规划 Buttom-up
/**if(triangle == null || triangle.size() == 0){
    return 0;
}

int n = triangle.size();

int [][] sum = new int[n][n];

for(int i = 0; i < n; i++){
    sum[n-1][i] = triangle.get(n-1).get(i);
}

for(int i = n-2; i >= 0; i--){
    for(int j = 0; j <= i; j++){
        sum[i][j] = Math.min(sum[i+1][j],sum[i+1][j+1]) + triangle.get(i).get(j);
    }
}
return sum[0][0];
*/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值