zoukankan      html  css  js  c++  java
  • 120. Triangle(Array; DP)

    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.

    思路:与119题类似,只是现在DP中存储的不是数组的值,而是到目前为止的minimum sum。赋值DP时为了避免改变上一行结果,也是得从右往左

    class Solution {
    public:
        int minimumTotal(vector<vector<int>>& triangle) {
            if(triangle.empty()) return 0;
            
            int minValue = INT_MAX;
            vector<int> dp(triangle.size());
            dp[0]=triangle[0][0];
            for(int i = 1; i < dp.size(); i++){
                dp[i] = dp[i-1]+triangle[i][i];
                for(int j = i-1; j > 0; j--){
                    dp[j] = min(dp[j-1],dp[j])+triangle[i][j];
                }
                dp[0] += triangle[i][0];
            }
            
            for(int i = 0; i < dp.size(); i++){
                if(dp[i] < minValue){
                    minValue = dp[i];
                }
            }
            
            return minValue;
        }
    };
  • 相关阅读:
    super与this的比较
    队列学习小结
    最左原则
    show processlist
    循环
    打印偶数
    发布模块
    eval函数
    文件
    模块
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4915386.html
Copyright © 2011-2022 走看看