[LeetCode]Minimum Path Sum,解題報告
阿新 • • 發佈:2019-01-24
前言
這道題目我今年面試的時候考過,不給出具體的哪家公司了,也是給定矩陣從左上角到右下角的和最小的路徑。 開始我並不知道是確定了起始點和結束點,因此我第一反應是用DFS遍歷矩陣,然後那個面試官說不讓我用遞迴(其實dfs也不一定非用遞迴實現)。想了一下我說用動態規劃,給他寫了狀態方程,時間複雜度為O(n^2),他非跟我糾結用動態規劃可以到O(n)的時間複雜度,我表示無語。雖然最後我還是拿到了這家的offer,不過面試官的水平讓我有些失望,最終還是沒去題目
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.Note: You can only move either down or right at any point in time.
思路
AC程式碼
import java.util.Scanner; public class MinimunPathSum { public static void main(String[] args) { int i, j, m, n, sum, grid[][]; Scanner cin = new Scanner(System.in); while (cin.hasNext()) { m = cin.nextInt(); n = cin.nextInt(); grid = new int[m][n]; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { grid[i][j] = cin.nextInt(); } } sum = minPathSum(grid); System.out.println(sum); } cin.close(); } public static int minPathSum(int[][] grid) { int i, j, dp[][] = new int[grid.length][grid[0].length]; int col, row; // initial variable row = grid.length; col = grid[0].length; // initial dp array dp[0][0] = grid[0][0]; for (i = 1; i < row; i++) { dp[i][0] = dp[i - 1][0] + grid[i][0]; } for (j = 1; j < col; j++) { dp[0][j] = dp[0][j - 1] + grid[0][j]; } // dynamic process, dp[i][j] = MIN{dp[i - 1][j], dp[i][j - 1]} + grid[i][j] for (i = 1; i < row; i++) { for (j = 1; j < col; j++) { dp[i][j] = dp[i - 1][j] <= dp[i][j - 1] ? dp[i - 1][j] + grid[i][j] : dp[i][j - 1] + grid[i][j]; } } return dp[row - 1][col - 1]; } }