剑指 Offer II 100. 三角形中最小路径之和

2022-07-13  本文已影响0人  邦_

func minimumTotal(_ triangle: [[Int]]) -> Int {
        
        let n = triangle.last?.count ?? 0
        let temp = Array.init(repeating: 0, count: n)
        var dp = Array.init(repeating: temp, count: n)
        for i in 0..<n {
            for j in 0..<n {
                if i == 0 && j == 0 {
                    dp[0][0] = triangle[0][0]
                }else if i == 0 {
                    
                    dp[0][j] = dp[0][j - 1] + triangle[j].last!
                }else if j == 0 {
                    
                    dp[i][0] = dp[i - 1][0] + triangle[i][0]
                }else {
                      //会发现纵坐标是相同的,横坐标是i + j
                    if (i + j < n) && j < triangle[i+j].count {
                        dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + triangle[i+j][j]
                    }  
                }
            }
            
        }
        var minValue = 0
        
        for i in 0..<n {
            if i == 0 {
                minValue = dp[i][n - i - 1]
            }else {
                minValue = min(dp[i][n - i - 1],minValue)

            }
        }
        
        return minValue
    
    
    }










上一篇下一篇

猜你喜欢

热点阅读