给出一个三角形(数据数组),找出从上往下的最小路径和。每一步只能移动到下一行中的相邻结点上。
比如,给你如下三角形:
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
则从上至下最小路径和为 11(即,2 + 3 + 5 + 1 = 11)
注意:
加分项:如果你可以只使用 O(n) 的额外空间(n是三角形的行数)。
详见:https://leetcode.com/problems/triangle/description/

Java实现:

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int row=triangle.size();//行数
        if(row==0){
            return 0;
        } 
         
        int[] res=new int[row+1];//倒着求,求最后一行到第一行最小和,这样就可以用o(n)空间了
         
        for(int i=row-1;i>=0;--i){
            List<Integer> list=triangle.get(i);
            for(int j=0;j<list.size();++j){
                res[j]=Math.min(res[j+1],res[j])+list.get(j);
            }
        } 
        return res[0];
    }
}

 参考:https://www.cnblogs.com/grandyang/p/4286274.html

相关文章:

  • 2021-12-01
  • 2021-10-08
  • 2021-06-10
  • 2021-09-26
  • 2021-11-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-30
  • 2021-09-06
  • 2021-07-02
  • 2022-01-01
  • 2021-09-14
相关资源
相似解决方案