zoukankan      html  css  js  c++  java
  • [leetcode]120.Triangle三角矩阵从顶到底的最小路径和

    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).
    动态规划题目
    定义一个二维数组记录当前位置到最后一行的数值,然后从下往上算,即s[i][j]代表i,j到最后一行的最小值,这里 选择从下往上是要比从上往下好的
    如果从上往下算的话需要判断上一行此处的值是否存在,因为是三角形
    * 公式:s[i][j] = t[i][j] + min(s[i+1][j] ,s[i+1][j+1])
    * 最后s[0][0]就是最后的结果
    public int minimumTotal(List<List<Integer>> triangle) {
            int l = triangle.size();
            int n = triangle.get(l-1).size();
            //特殊情况
            if (l ==0 || n==0)
                return 0;
            int[][] res = new int[l][n];
            //初始条件
            for (int i = 0;i < n;i++)
            {
                res[l-1][i] = triangle.get(l-1).get(i);
            }
            //动态规划主体
            for (int i = l-2; i >= 0; i--) {
                for (int j = 0;j < triangle.get(i).size();j++)
                {
                    res[i][j] = Math.min(res[i+1][j],res[i+1][j+1]) + triangle.get(i).get(j);
                }
            }
            return res[0][0];
        }
  • 相关阅读:
    jsonp
    web系统中上下移动功能的实现
    重载的目的是什么
    重写和重载
    final和static
    static的应用
    shiro认证
    做阉割版Salesforce难成伟大的TOB企业
    Go语言在国产CPU平台上应用前景的探索与思考
    101 More Security Best Practices for Kubernetes
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7373527.html
Copyright © 2011-2022 走看看