Link 931.Minimum Falling Path Sum
Thought
DFS
When first seeing this question, DFS prompt into my mind directly. Take Any node from first level as start, and search down stream. Until reach node in last level. For any path, it will have a value. Find the minimum value and it will be the answer
However, for any node, it has 3 paths -> go left lower, go right lower and go direct lower. So if I have N nodes per level, the time complexity is O(3^N) which cause TLE.
DP
Then, I find for any node, I dont quite care how it comes from the top level. What I do care is the minimum value, from any node at first level, pass level by level, then end at a specific node. So I don’t need to calculate again and again.
State Transfer Equation:
DP[i][j] = min(DP[i-1][j-1], DP[i-1][j], DP[i-1][j+1]) + Value[i][j]
Code
class Solution: def minFallingPathSum(self, A): """ :type A: List[List[int]] :rtype: int """ M = len(A) N = len(A[0]) for i in range(1, M): for j in range(N): if j == 0: A[i][j] = min(A[i-1][j], A[i-1][j+1]) + A[i][j] elif j == N - 1: A[i][j] = min(A[i-1][j], A[i-1][j-1]) + A[i][j] else: A[i][j] = min((A[i-1][j], A[i-1][j+1],A[i-1][j-1],)) + A[i][j] return min(A[-1])
Runtime
Time O(N^2)
Space O(N^2)