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

    在输入的数组中直接修改,这样就不需要额外的空间了,不知道这样符合题目的本意不,不过已AC。

     1 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> > &triangle) {
     4         if (triangle.size() == 1) {
     5             return triangle[0][0];
     6         }
     7         int min_sum = INT_MAX;
     8         for (int i = 1; i < triangle.size(); ++i) {
     9             for (int j = 0; j <= i; ++j) {
    10                 if (j == 0) {
    11                     triangle[i][j] += triangle[i-1][j];
    12                 } else if (j == i) {
    13                     triangle[i][j] += triangle[i-1][j-1];
    14                 } else {
    15                     triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]);
    16                 }
    17                 if (i == triangle.size() - 1) {
    18                     min_sum = min(min_sum, triangle[i][j]);
    19                 }
    20             }
    21         }
    22         return min_sum;
    23     }
    24 };
  • 相关阅读:
    python count函数
    kubenetes服务发现
    k8s网络
    k8s创建pod流程
    openstack创建虚拟流程、各组件介绍
    生产者消费者问题
    Date类和Calendar类
    Timer定时器
    Java中的克隆
    注解
  • 原文地址:https://www.cnblogs.com/easonliu/p/3637367.html
Copyright © 2011-2022 走看看