这里会给出关于动规的一些常见题型和变种,给自己做一个参考:
Leetcode #62. Unique Paths 路径搜寻 解题报告
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).
How many possible unique paths are there?
2、思路1
因为每一步只能向右或向下走,因此,可以将状态A[i][j]定义为走到位置[i][j]有A[i][j]种路径,因此状态转移方程为A[i][j] = A[i - 1][j] + A[i][j - 1]
然后问题只剩下初始状态的定义,由于每一步只能向下或向右,因此,A[0]i=1,A[j]0 = 1;好了,现在有了1.状态定义;2.状态转移公式;3.初始状态.通过代码运行就可以得到要求解的状态A[m-1][n-1].
public class Solution {
public int uniquePaths(int m, int n) {
int[][] dp=new int[m][n];
int i,j;
for(i=0;i<n;i++)
dp[0][i]=1;
for(i=0;i<m;i++)
dp[i][0]=1;
for(i=1;i<m;i++){
for(j=1;j<n;j++){
dp[i][j]=dp[i-1][j]+dp[i][j-1]; } }
return dp[m-1][n-1];
}}
思路2.采用排列组合的思想
对于m*n的格子,一样的,就是从m+n步中选出m步向下或n步向右,因此为C(m+n,m)=C(m+n,n)种。
变形1.63. Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
这道题相比较上一道题,有的地方是不能走的,使用对应矩阵当中1来标示。
与上题类似,如果不能走,A[i][j] = 0,因此,只需要加一个判读条件就好。
代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m=obstacleGrid.size();
int n=obstacleGrid[0].size();
vector<vector<int>> dp(m,vector<int>(n,0));
int i=0,j;
while(i<n && obstacleGrid[0][i]==0){
dp[0][i++]=1;
}
i=0;
while(i<m && obstacleGrid[i][0]==0){
dp[i++][0]=1;
}
for(i=1;i<m;i++){
for(j=1;j<n;j++){
if(obstacleGrid[i][j]==0)
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
变形3:Leetcode 64. Minimum Path
题目: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.
(感觉只要是只能向下和向右走的都可以用这种思想啊)
代码:
public class Solution {
public int minPathSum(int[][] grid) {
if(grid.length==0 || grid[0].length==0)
return 0;
int m=grid.length;
int n=grid[0].length;
int dp[][]=new int[m][n];
int top,left;
int i=0,j;
dp[0][0]=grid[0][0];
for( j=1;j<n;j++){
dp[i][j]=dp[i][j-1]+grid[i][j];
}
for( j=1;j<m;j++){
dp[j][i]=dp[j-1][i]+grid[j][i];
}
for( i=1;i<m;i++){
for( j=1;j<n;j++){
top=Integer.MAX_VALUE;
left=Integer.MAX_VALUE;
top=dp[i-1][j];
left=dp[i][j-1];
dp[i][j]=Math.min(top,left)+grid[i][j];
}
}
return dp[m-1][n-1];
}
}
网友评论