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.
1var minFallingPathSum = function(matrix) {
2 const n = matrix.length;
3 for (let i = n - 2; i >= 0; i--) {
4 for (let j = 0; j < n; j++) {
5 let best = matrix[i + 1][j];
6 if (j > 0) best = Math.min(best, matrix[i + 1][j - 1]);
7 if (j < n - 1) best = Math.min(best, matrix[i + 1][j + 1]);
8 matrix[i][j] += best;
9 }
10 }
11 return Math.min(...matrix[0]);
12};
13
JavaScript solution accumulates the minimum path sums by modifying the matrix from the bottom row up and finally finds the minimum sum in the top row.
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 private int[][] memo;
public int MinFallingPathSum(int[][] matrix) {
int n = matrix.Length;
memo = new int[n][];
for (int i = 0; i < n; i++) {
memo[i] = new int[n];
for (int j = 0; j < n; j++) {
memo[i][j] = int.MaxValue;
}
}
int minSum = int.MaxValue;
for (int col = 0; col < n; col++) {
minSum = Math.Min(minSum, Dfs(matrix, 0, col));
}
return minSum;
}
private int Dfs(int[][] matrix, int row, int col) {
int n = matrix.Length;
if (row == n) return 0;
if (memo[row][col] != int.MaxValue) return memo[row][col];
int res = matrix[row][col] + Dfs(matrix, row + 1, col);
if (col > 0) res = Math.Min(res, matrix[row][col] + Dfs(matrix, row + 1, col - 1));
if (col < n - 1) res = Math.Min(res, matrix[row][col] + Dfs(matrix, row + 1, col + 1));
memo[row][col] = res;
return res;
}
}
The C# solution explores the use of memoization to optimize recursive calculations and cache intermediate results, ensuring no repeated computations occur.