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: }


  • 相关阅读:
    java的类继承(与c++对比)
    java的数据类型、自动拆装箱、字面量
    java中关键字static和final
    JVM之JIT
    java之JIT(Just in time)
    栈和堆
    C++中vector的使用
    canvas
    ajax笔记
    CSS笔记
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078941.html
Copyright © 2011-2022 走看看