triangle

来源:互联网 发布:搜云社工库11g数据库 编辑:程序博客网 时间:2024/06/04 01:31

容易 数字三角形

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
原创粉丝点击