今天是第三十九天,只有两道动态规划的题
class Solution { public int uniquePaths(int m, int n) { int[][] path = new int[m][n]; for(int i = 0; i<m; i++){ path[i][0] = 1; } for(int j = 0; j< n; j++){ path[0][j] = 1; } for(int i = 1; i<m; i++){ for(int j = 1; j<n; j++){ path[i][j] = path[i-1][j] + path[i][j-1]; } } return path[m-1][n-1]; } }
和走楼梯一样,记录下每一条路径的到达方法个数,然后把上面的格子和左边格子的都加起来。有边界的话要先把值设为1。
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int n = obstacleGrid.length; int m = obstacleGrid[0].length; if(obstacleGrid[n-1][m-1]==1||obstacleGrid[0][0]==1){ return 0; } for(int i = 0; i<n; i++){ for(int j = 0; j< m; j++){ if(obstacleGrid[i][j]==1){ obstacleGrid[i][j] = -1; } } } obstacleGrid[0][0] = 1; for(int i = 1; i<n; i++){ if(obstacleGrid[i][0]!=-1&&obstacleGrid[i-1][0]==1){ obstacleGrid[i][0] = 1; } } for(int j = 1; j< m; j++){ if(obstacleGrid[0][j]!=-1&&obstacleGrid[0][j-1]==1){ obstacleGrid[0][j] = 1; } } for(int i = 1; i< n; i++){ for(int j = 1; j< m; j++){ if(obstacleGrid[i][j]!=-1){ if(obstacleGrid[i-1][j]!=-1){ obstacleGrid[i][j] += obstacleGrid[i-1][j]; } if(obstacleGrid[i][j-1]!=-1){ obstacleGrid[i][j] += obstacleGrid[i][j-1]; } } } } return obstacleGrid[n-1][m-1]; } }
和上道题一样,每个格子只有在自己本身不是障碍物和前面的格子不是障碍物的情况下,才加上前面盒子的路径
今天是两道medium,都不难,但是要把情况都考虑到
标签:obstacleGrid,格子,int,代码,第三十九,随想录,路径 From: https://www.cnblogs.com/catSoda/p/16907687.html