[Swift Weekly Contest 108]LeetCode931. 下降路徑最小和 | Minimum Falling Path Sum
阿新 • • 發佈:2018-10-28
put one 元素 tput 輸出 給定 想要 rev ...
, so the answer is
Given a square array of integers A
, we want the minimum sum of a falling path through A
.
A falling path starts at any element in the first row, and chooses one element from each row. The next row‘s choice must be in a column that is different from the previous row‘s column by at most one.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation:
The possible falling paths are:
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
The falling path with the smallest sum is [1,4,7]
12
.
Note:
1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100
給定一個方形整數數組 A
,我們想要得到通過 A
的下降路徑的最小和。
下降路徑可以從第一行中的任何元素開始,並從每一行中選擇一個元素。在下一行選擇的元素和當前行所選元素最多相隔一列。
示例:
輸入:[[1,2,3],[4,5,6],[7,8,9]] 輸出:12 解釋: 可能的下降路徑有:
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
和最小的下降路徑是 [1,4,7]
,所以答案是 12
。
提示:
1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100
196ms
1 class Solution { 2 func minFallingPathSum(_ A: [[Int]]) -> Int { 3 let m:Int = A[0].count 4 var dp:[Int] = A[0] 5 for j in 0..<(A.count - 1) 6 { 7 var row:[Int] = A[j] 8 var ndp:[Int] = [Int](repeating: Int.max / 2,count: m) 9 for i in 0..<m 10 { 11 for k in -1...1 12 { 13 if i+k >= 0 && i+k < m 14 { 15 ndp[i + k] = min(ndp[i + k], dp[i] + A[j + 1][i + k]) 16 } 17 } 18 } 19 dp = ndp 20 } 21 var ret:Int = Int.max 22 for v in dp 23 { 24 ret = min(ret, v) 25 } 26 return ret 27 } 28 }
[Swift Weekly Contest 108]LeetCode931. 下降路徑最小和 | Minimum Falling Path Sum