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).

     1 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> > &triangle) {
     4         int size = triangle.size();
     5         vector<int> table(size, 0);
     6         for (int i = 0; i < size; ++i) {
     7             table[i] = triangle[size - 1][i];
     8         }
     9         for (int i = size - 2; i >= 0; --i) {
    10             for (int j = 0; j <= i; ++j) {
    11                 table[j] = min(table[j], table[j + 1]) + triangle[i][j];
    12             }
    13         }
    14         return table[0];
    15     }
    16 };
    View Code

    自底向上dp. 如果允许改变三角形本身,直接利用其本身空间即可。

  • 相关阅读:
    iOS_03_为什么选择ios开发
    iOS_02_什么是ios开发
    iOS_01_什么是ios
    Hadoop之HDFS
    hadoop组件及其作用
    数组
    Scala基础知识(二)
    hadoop安装过程
    Scala基础知识
    建造者模式
  • 原文地址:https://www.cnblogs.com/dengeven/p/3740842.html
Copyright © 2011-2022 走看看