1. 线性DP 120. 三角形最小路径和

经典问题:

120. 三角形最小路径和  https://leetcode-cn.com/problems/triangle/

func minimumTotal(triangle [][]int) int {
    n := len(triangle)
    dp := make([][]int,n)
    for i:=0;i<n;i++{
        dp[i] = make([]int,i+1)
    }
    dp[0][0] = triangle[0][0]
    for i:=1;i<n;i++{
        for j:=0;j<=i;j++{
            if j==0 {
                dp[i][j] = dp[i-1][j]+triangle[i][j]
            }else if j==i{
                dp[i][j] = dp[i-1][j-1] + triangle[i][j]
            }else{
                dp[i][j] = MIN(dp[i-1][j-1]+triangle[i][j],dp[i-1][j]+triangle[i][j]) 
            }
        }
    }
    res := dp[n-1][0]
    for j:=0;j<=n-1;j++{
        res = MIN(res,dp[n-1][j])
    }
    return res
}

func MIN(i,j int) int{
    if i<j{
        return i
    }else{
        return j
    }
}

  

posted on 2020-04-19 23:18  wsw_seu  阅读(111)  评论(0编辑  收藏  举报

导航