zoukankan      html  css  js  c++  java
  • 动态规划—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 is11(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.

    思路:

    题目的意思是找出从顶到底的最小路径和,类似二叉树。

    从下向上进行,例如第i+1行的第j和j+1元素进行比较,将两元素中较小的值与第i行的第j个元素相加,以此类推,最后顶元素就是要求的最小路径和。

    代码:

     1 public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
     2         int row = triangle.size();
     3         for(int i=row-2;i>=0;i--){
     4             for(int j=0;j<=i;j++){
     5                 int min = Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1));
     6                 triangle.get(i).set(j, triangle.get(i).get(j)+min);
     7             }
     8         }
     9         return triangle.get(0).get(0);
    10 }
  • 相关阅读:
    Bootstrap按钮
    Bootstrap表单
    Bootstrap表格
    Bootstrap列表
    jq 的onchange事件
    php 跳出循环的几种方式
    php变量和字符串连接符——点
    php 从2维数组组合为四维数组分析
    mysql 删除表中记录
    mysql 聚合函数
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/7458617.html
Copyright © 2011-2022 走看看