Sponsored
Sponsored
Using a dynamic programming matrix, you can start from the second-last row of the matrix and calculate the minimum path sum by traversing through possible paths (directly below, diagonally left, and diagonally right). Update the matrix in-place to use constant space.
Time Complexity: O(n^2) because each element is visited once.
Space Complexity: O(1) since the computations are done in place.
1class Solution {
2 public int minFallingPathSum(int[][] matrix) {
3 int n = matrix.length;
4 for (int i = n - 2; i >= 0; i--) {
5 for (int j = 0; j < n; j++) {
6 int best = matrix[i + 1][j];
7 if (j > 0) best = Math.min(best, matrix[i + 1][j - 1]);
8 if (j < n - 1) best = Math.min(best, matrix[i + 1][j + 1]);
9 matrix[i][j] += best;
10 }
11 }
12 int minSum = Integer.MAX_VALUE;
13 for (int val : matrix[0]) {
14 minSum = Math.min(minSum, val);
15 }
16 return minSum;
17 }
18}
19
In Java, the solution involves modifying the original matrix to maintain minimal path sums. The minimum sum in the top row indicates the answer.
For this approach, we use recursion with memoization to explore paths starting from the first row to the last row. We store intermediate results to avoid redundant calculations.
Time Complexity: O(n^2) due to memoization reducing redundant calculations.
Space Complexity: O(n^2) due to the memoization table.
1
The Java approach uses recursive dynamic programming with memoization to efficiently solve the problem by storing intermediate results in a 2D array to prevent recalculations.