Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
publicclassSolution{ publicintuniquePaths(int m, int n){ if(m == 1 || n == 1) return1; m--; n--; if(m < n) { // Swap, so that m is the bigger number m = m + n; n = m - n; m = m - n; } long res = 1; int j = 1; for(int i = m+1; i <= m+n; i++, j++){ // Instead of taking factorial, keep on multiply & divide res *= i; res /= j; } return (int)res; } }
动态规划代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution{ publicintuniquePaths(int m, int n){ Integer[][] map = new Integer[m][n]; for(int i = 0; i<m;i++){ map[i][0] = 1; } for(int j= 0;j<n;j++){ map[0][j]=1; } for(int i = 1;i<m;i++){ for(int j = 1;j<n;j++){ map[i][j] = map[i-1][j]+map[i][j-1]; } } return map[m-1][n-1]; } }
Input: [ [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. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right
int R = obstacleGrid.length; int C = obstacleGrid[0].length;
// If the starting cell has an obstacle, then simply return as there would be // no paths to the destination. if (obstacleGrid[0][0] == 1) { return0; }
// Number of ways of reaching the starting cell = 1. obstacleGrid[0][0] = 1;
// Filling the values for the first column for (int i = 1; i < R; i++) { obstacleGrid[i][0] = (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) ? 1 : 0; }
// Filling the values for the first row for (int i = 1; i < C; i++) { obstacleGrid[0][i] = (obstacleGrid[0][i] == 0 && obstacleGrid[0][i - 1] == 1) ? 1 : 0; }
// Starting from cell(1,1) fill up the values // No. of ways of reaching cell[i][j] = cell[i - 1][j] + cell[i][j - 1] // i.e. From above and left. for (int i = 1; i < R; i++) { for (int j = 1; j < C; j++) { if (obstacleGrid[i][j] == 0) { obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]; } else { obstacleGrid[i][j] = 0; } } }
// Return value stored in rightmost bottommost cell. That is the destination. return obstacleGrid[R - 1][C - 1]; } }