Created
June 3, 2015 19:04
-
-
Save cangoal/c6444642bdf394281580 to your computer and use it in GitHub Desktop.
LeetCode - Unique Paths II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| public int uniquePathsWithObstacles(int[][] obstacleGrid) { | |
| if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) | |
| return 0; | |
| int m = obstacleGrid.length, n = obstacleGrid[0].length; | |
| int[] res = new int[n]; | |
| if(obstacleGrid[0][0] == 0) res[0] = 1; | |
| else res[0] = 0; | |
| for(int i=0;i<m;i++) | |
| { | |
| if(obstacleGrid[i][0] == 0) res[0] = res[0]; | |
| else res[0] = 0; | |
| for(int j=1;j<n;j++) | |
| { | |
| if(obstacleGrid[i][j] == 1){ | |
| res[j] = 0; | |
| }else{ | |
| res[j] += res[j-1]; | |
| } | |
| } | |
| } | |
| return res[n-1]; | |
| } | |
| // better solution | |
| public int uniquePathsWithObstacles(int[][] obstacleGrid) { | |
| int m = obstacleGrid.length; | |
| int n = obstacleGrid[0].length; | |
| int[][] mat = new int[m+1][n+1]; | |
| mat[0][1] = 1; | |
| for(int i=1; i<=m; i++){ | |
| for(int j=1; j<=n; j++){ | |
| if(obstacleGrid[i-1][j-1]!=1) | |
| mat[i][j] = mat[i-1][j]+mat[i][j-1]; | |
| } | |
| } | |
| return mat[m][n]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment