zoukankan      html  css  js  c++  java
  • [LeetCode] 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).
    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.
    » Solve this problem

    [解题思路]

    一维DP。逐行扫描,每一个位置能取得的最小sum,是该元素上面两个能取得的最小sum中最小的那一个sum加上自己的值。只需要开一个数组重复利用就行了。

    实现的时候,有些繁琐的地方,这个题比较好从下往上扫描。如果从上往下,其中minV的初始值问题就很头疼。


    [Code]

    1:    int minimumTotal(vector<vector<int> > &triangle) {  
    2: int row = triangle.size();
    3: if(row ==0) return 0;
    4: vector<int> minV(triangle[row-1].size());
    5: for(int i =row-1; i>=0; i--)
    6: {
    7: int col = triangle[i].size();
    8: for(int j =0; j<col; j++)
    9: {
    10: if(i == row-1)
    11: {
    12: minV[j] = triangle[i][j];
    13: continue;
    14: }
    15: minV[j] = min(minV[j], minV[j+1]) + triangle[i][j];
    16: }
    17: }
    18: return minV[0];
    19: }


  • 相关阅读:
    msyql 死锁
    yii2 操作数据库
    yii2 加载静态资源
    Yii2 之 UrlManager 实践 (一)
    Wordpress 之 Rewrite Rules
    yii2 使用gii生成代码文件
    权限设计的杂谈
    NodeJS —— 自定义流的实现
    浅析递归
    请将你的App签名文件放进保险箱
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078941.html
Copyright © 2011-2022 走看看