zoukankan      html  css  js  c++  java
  • leetcode 120. Triangle

    leetcode 120. 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.

    solution

    动态规划
    状态转移方程为
    位置{i}处的最小值要么是左边来的要么是右边来的
    dp[i]=min{dp[left], dp[right]}+nowLocation

    class Solution {
    public:
        int minimumTotal(vector<vector<int>>& triangle) {
            int n = triangle.size();
            int dp[n+1][n+1];
            for(int i = 1; i <= n ;i++)
                dp[1][i] = triangle[n-1][i-1];
            for(int i = 2; i <= n; i++)
                for(int j = 1; j <= n-i+1; j++)
                {
                    dp[i][j] = (dp[i-1][j] < dp[i-1][j+1] ? dp[i-1][j] : dp[i-1][j+1]) + triangle[n-i][j-1];
                }
            return dp[n][1];        
        }
    
    blogs record our growth
  • 相关阅读:
    Linux-Rsync命令参数详解
    Linux-iptables(2)
    Linux-iptables
    Linux-awk command
    Linux-sed command
    Linux-tomcat
    C#调用默认浏览器打开网页的几种方法
    个人记录用
    .NET中的Request
    sql标量值函数,将汉字转化为拼音,无音标
  • 原文地址:https://www.cnblogs.com/qwfand/p/12669572.html
Copyright © 2011-2022 走看看