64.Minimum Path Sum---dp

題目連接:https://leetcode.com/problems/minimum-path-sum/description/ide

題目大意:從左上到右下的路徑中,找出路徑和最小的路徑(與62,63題相聯繫)。spa

法一:dfs,果真超時,無剪枝。代碼以下:code

 1     public int minPathSum(int[][] grid) {
 2         boolean vis[][] = new boolean[grid.length][grid[0].length];
 3         int f[][] = {{1, 0}, {0, 1}};
 4         return dfs(grid, 0, 0, grid[0][0], Integer.MAX_VALUE, vis, f);
 5     }
 6     public static int dfs(int[][] grid, int x, int y, int sum, int res, boolean vis[][], int f[][]) {
 7         if(sum >= res) {
 8             return res;
 9         }
10         if(x == grid.length - 1 && y == grid[0].length - 1) {
11             if(sum < res) {
12                 res = sum;
13             }
14             return res;
15         }
16         for(int i = 0; i < 2; i++) {
17             int cnt_x = x + f[i][0];
18             int cnt_y = y + f[i][1];
19             if(cnt_x < grid.length && cnt_y < grid[0].length && vis[cnt_x][cnt_y] == false) {
20                 vis[cnt_x][cnt_y] = true;
21                 res = dfs(grid, cnt_x, cnt_y, sum + grid[cnt_x][cnt_y], res, vis, f);
22                 vis[cnt_x][cnt_y] = false;
23             }
24         }
25         return res;
26     }
View Code

法二:dp,模仿62的二維dp,只是這裏dp[i][j]表示到終點座標爲[i,j]的最短路徑和,dp公式爲dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j]。代碼以下(耗時9ms):blog

 1     public int minPathSum(int[][] grid) {
 2         int dp[][] = new int[grid.length][grid[0].length];
 3         //初始化第一列
 4         dp[0][0] = dp[0][0] = grid[0][0];
 5         for(int i = 1; i < grid.length; i++) {
 6             dp[i][0] = dp[i - 1][0] + grid[i][0];
 7         }
 8         //初始化第一行
 9         for(int i = 1; i < grid[0].length; i++) {
10             dp[0][i] = dp[0][i - 1] + grid[0][i];
11         }
12         //計算dp
13         for(int i = 1; i < grid.length; i++) {
14             for(int j = 1; j < grid[0].length; j++) {
15                 //取從左邊和從上邊到達的最短路徑+當前值
16                 dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
17             }
18         }
19         return dp[grid.length - 1][grid[0].length - 1];
20     }
View Code

法三:一維dp,代碼以下(耗時9ms):ip

 1     public int minPathSum(int[][] grid) {
 2         int[] dp = new int[grid[0].length];
 3         //初始化第一行
 4         dp[0] = grid[0][0];
 5         for(int j = 1; j < grid[0].length; j++) {
 6             dp[j] = grid[0][j] + dp[j - 1];
 7         }
 8         //從第一行第0列開始計算
 9         for(int i = 1; i < grid.length; i++) {
10             //計算第0列
11             dp[0] += grid[i][0];
12             //從第1列開始
13             for(int j = 1; j < grid[0].length; j++) {
14                 dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
15             }
16         }
17         return dp[grid[0].length - 1];
18     }
View Code
相關文章
相關標籤/搜索