zoukankan      html  css  js  c++  java
  • LintCode: Triangle

    C++

    逆推

     1 class Solution {
     2 public:
     3     /**
     4      * @param triangle: a list of lists of integers.
     5      * @return: An integer, minimum path sum.
     6      */
     7     int minimumTotal(vector<vector<int> > &triangle) {
     8         // write your code here
     9         if (triangle.size() == 0)
    10             return 0;
    11             
    12         vector<int> dp(triangle.size());
    13         
    14         dp[0] = triangle[0][0];
    15         for(int i = 1; i < triangle.size(); i++)
    16             for(int j = triangle[i].size() - 1; j >= 0; j--)
    17                 if (j == 0)
    18                     dp[j] = dp[j] + triangle[i][j];
    19                 else if (j == triangle[i].size() - 1)
    20                     dp[j] = dp[j-1] + triangle[i][j];
    21                 else
    22                     dp[j] = min(dp[j-1], dp[j]) + triangle[i][j];
    23                     
    24         int ret = INT_MAX;
    25         for(int i = 0; i < dp.size(); i++)
    26             ret = min(ret, dp[i]);
    27             
    28         return ret;  
    29     }
    30 };

     C++,修改原数组

     1 class Solution {
     2 public:
     3     /**
     4      * @param triangle: a list of lists of integers.
     5      * @return: An integer, minimum path sum.
     6      */
     7     int minimumTotal(vector<vector<int> > &triangle) {
     8         // write your code here
     9         for (int i = triangle.size() - 2; i >= 0; --i){
    10           for (int j = 0; j < i + 1; ++j){
    11             if(triangle[i+1][j] > triangle[i+1][j+1]){
    12               triangle[i][j] += triangle[i+1][j+1];
    13             }else{
    14               triangle[i][j] += triangle[i+1][j];
    15             }
    16           }
    17         }
    18         return triangle[0][0];
    19     }
    20 };
  • 相关阅读:
    PHP之ThinkPHP框架(界面)
    安卓网络访问(xUtils3)
    Python制作二维码和条形码扫描器 (pyzbar)
    redis 哨兵
    Django 源码阅读笔记(详细视图)
    Django 源码阅读笔记(基础视图)
    JavaScript基础
    Flask 基础
    redis 主从复制
    redis 数据删除策略和逐出算法
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5006838.html
Copyright © 2011-2022 走看看