https://leetcode.com/problems/minimum-falling-path-sum/
https://leetcode.com/problems/minimum-falling-path-sum/discuss/186666/C%2B%2BJava-4-lines-DP
https://leetcode.com/problems/minimum-falling-path-sum/discuss/186651/Java-two-clean-DP-codes-input-modified-and-not-Time-O(n-2)-space-O(1)-and-O(n
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]
, so the answer is 12
.
This problem has an optimal substructure, meaning that the solutions to subproblems can be used to solve larger instances of this problem. This makes dynamic programming an ideal candidate.
Let
dp(r, c)
be the minimum total weight of a falling path starting at (r, c)
and reaching the bottom row.
Then,
dp(r, c) = A[r][c] + min(dp(r+1, c-1), dp(r+1, c), dp(r+1, c+1))
, and the answer is .
public int minFallingPathSum(int[][] A) {
int N = A.length;
for (int r = N - 2; r >= 0; --r) {
for (int c = 0; c < N; ++c) {
// best = min(A[r+1][c-1], A[r+1][c], A[r+1][c+1])
int best = A[r + 1][c];
if (c > 0)
best = Math.min(best, A[r + 1][c - 1]);
if (c + 1 < N)
best = Math.min(best, A[r + 1][c + 1]);
A[r][c] += best;
}
}
int ans = Integer.MAX_VALUE;
for (int x : A[0])
ans = Math.min(ans, x);
return ans;
}
https://leetcode.com/problems/minimum-falling-path-sum/discuss/186666/C%2B%2BJava-4-lines-DP
Method 1: input modified.
Time:
Time:
O(n ^ 2)
, space: O(1)
- Starting from 2nd row, for each element, choose to add the minimum of the above 3 (or 2 if at either end of the row);
- Repeat till the last row;
- Find the minimum out of the last row.