Topics are as follows:
Given a square grid of integers
arr
, a falling path with non-zero shifts is a choice of exactly one element from each row ofarr
, such that no two elements chosen in adjacent rows are in the same column.Return the minimum sum of a falling path with non-zero shifts.
Example 1:
Input: arr = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Explanation: The possible falling paths are: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] The falling path with the smallest sum is [1,5,7], so the answer is 13.Constraints:
1 <= arr.length == arr[i].length <= 200
-99 <= arr[i][j] <= 99
Outline of Solution: referred DP [i] [j] is the i-th row j-th element takes the minimum value obtained in the 0 ~ i line intervals. Then clearly dp [i] [j] = min (dp [i] [j], dp [i-1] [k] + arr [i] [j]), where j! = K. In this case time complexity is O (n), the time-out. Think again, in fact, for any j, the dp [i-1] to find the minimum value as long as, of course, where the minimum value of the column and j can not be the same. Then only needs to record dp [i-1] and the minimum time line minimum value, and if the minimum value of the index j takes the same time to a small value, or minimum value.
code show as below:
class Solution(object): def minFallingPathSum(self, arr): """ :type arr: List[List[int]] :rtype: int """ dp = [[float('inf')] * len(arr) for _ in arr] for i in range(len(arr)): dp[0][i] = arr[0][i] def getMin(arr): min_val = float ( ' IFN ' ) min_inx = 0 for i in range(len(arr)): if min_val > arr[i]: min_val = arr [i] min_inx = in return (min_val, min_inx) def getSecMin(arr,min_inx): sec_min_val = float ( ' IFN ' ) sec_min_inx = 0 for i in range(len(arr)): if i == min_inx:continue if sec_min_val > arr[i]: sec_min_val = arr [i] sec_min_inx = in return (sec_min_val, sec_min_inx) for i in range(1,len(arr)): min_val, min_inx = getMin (dp [i-1 ]) sec_min_val, sec_min_inx = getSecMin(dp[i-1],min_inx) for j in range(len(arr)): if j == min_inx: dp[i][j] = min(dp[i][j],dp[i-1][sec_min_inx] + arr[i][j]) else: dp[i][j] = min(dp[i][j], dp[i - 1][min_inx] + arr[i][j]) return min(dp[-1])