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 }
  • 相关阅读:
    web前端图片上传
    二级联动
    前端框架
    获取URL域名
    监听横屏竖屏
    下载中间件、爬虫中间件
    起始url的调度原理
    自定义代理IP
    爬虫深度控制
    手动处理cookie(实现一个点赞爬虫)
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/7458617.html
Copyright © 2011-2022 走看看