64.Minimum Path Sum---dp

题目链接:https://leetcode.com/problems/minimum-path-sum/description/

题目大意:从左上到右下的路径中,找出路径和最小的路径(与62,63题相联系)。

法一:dfs,果然超时,无剪枝。代码如下:

 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):

 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):

 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

 

posted on 2018-03-01 11:27  二十年后20  阅读(106)  评论(0编辑  收藏  举报

导航