63. Unique Paths II and 64. Minimum Path Sum
文章目錄
- 1 63 Unique Paths II
- 1.1 題目描述
- 1.2 動態規劃解決
- 2 64. Minimum Path Sum
- 2.1 題目理解
- 2.2 動態規劃
這一遍刷dp的題目就很輕松了。
1 63 Unique Paths II
1.1 題目描述
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and space is marked as 1 and 0 respectively in the grid.
輸入:整數數組grid,表示一個mxn的方格,grid[i][j]=1表示是障礙,不能通過;grid[i][j]=0表示可以通過。
輸出:能夠從左上角走到右下角的不重復的路徑數
規則:只能向下或者向右走
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation: There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1.2 動態規劃解決
class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {if(obstacleGrid[0][0]==1) return 0;int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[][] dp = new int[m][n];dp[0][0] = (obstacleGrid[0][0]==1?0:1);for(int j=1;j<n;j++){dp[0][j]= (obstacleGrid[0][j]==1?0:dp[0][j-1]);}for(int i=1;i<m;i++){dp[i][0] = (obstacleGrid[i][0]==1?0:dp[i-1][0]);}for(int i=1;i<m;i++){for(int j=1;j<n;j++){dp[i][j] = (obstacleGrid[i][j]==0?dp[i-1][j]+dp[i][j-1]:0);}}return dp[m-1][n-1];} }2 64. Minimum Path Sum
2.1 題目理解
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.
輸入:整數數組grid,表示一個mxn的方格,grid[i][j]表示通過方格的代價。
輸出:能夠從左上角走到右下角的最小代價
規則:只能向下或者向右走
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
2.2 動態規劃
class Solution {public int minPathSum(int[][] grid) {int m = grid.length;int n = grid[0].length;int[][] dp = new int[m][n];dp[0][0] = grid[0][0];for(int i=1;i<m;i++){dp[i][0] = dp[i-1][0]+grid[i][0];}for(int j=1;j<n;j++){dp[0][j] = dp[0][j-1]+grid[0][j];}for(int i=1;i<m;i++){for(int j=1;j<n;j++){dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];}}return dp[m-1][n-1];} }總結
以上是生活随笔為你收集整理的63. Unique Paths II and 64. Minimum Path Sum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse 最佳字体 推荐
- 下一篇: myeclipse2014删除antlr