不同路径—动态规划
思路:第一行和第一列的元素都有一条路径可以到达,将对应位置赋值为1。接下来每个位置处都可以从其上边或左边到达。
1 int uniquePaths(int m, int n) { 2 // write your code here 3 int ** s = new int*[m]; 4 for (int i = 0; i < m; i++) { 5 s[i] = new int[n]; 6 } 7 for (int i = 0; i < m; i++) { 8 s[i][0] = 1; 9 } 10 for (int i = 0; i < n; i++) { 11 s[0][i] = 1; 12 } 13 for (int i = 1; i < m; i++) { 14 for (int j = 1; j < n; j++) { 15 s[i][j] = s[i-1][j] + s[i][j-1]; 16 } 17 } 18 return s[m-1][n-1]; 19 }
思路:第一行和第一列在没有遇到障碍时,都有一条路径可以到达,都设为1。但当第一行(列)某个位置遇到障碍时,该位置处和其右边(下边)位置处都不能到达了,都要设为0。接下来的位置,当遇到障碍时设为0,没有障碍时还是其上边的路径加上左边的路径。
1 int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) { 2 // write your code here 3 int row = obstacleGrid.size(); 4 int col = obstacleGrid[0].size(); 5 int ** s = new int*[row]; 6 for (int i = 0; i < row; i++) { 7 s[i] = new int[col]; 8 } 9 int t = 0, flag = 0; 10 for (int i = 0; i < row; i++) { 11 if (obstacleGrid[i][0] == 0) { 12 s[i][0] = 1; 13 } else { 14 s[i][0] = 0; 15 t = i; 16 flag = 1; 17 break; 18 } 19 } 20 if (flag == 1) { 21 for (int i = t; i < row; i++) { 22 s[i][0] = 0; 23 } 24 flag = 0; 25 } 26 27 for (int j = 0; j < col; j++) { 28 if (obstacleGrid[0][j] == 0) { 29 s[0][j] = 1; 30 } else { 31 s[0][j] = 0; 32 t = j; 33 flag = 1; 34 break; 35 } 36 } 37 if (flag == 1) { 38 for (int j = t; j < col; j++) { 39 s[0][j] = 0; 40 } 41 flag = 1; 42 } 43 for (int i = 1; i < row; i++) { 44 for (int j = 1; j < col; j++) { 45 if (obstacleGrid[i][j] == 0) { 46 s[i][j] = s[i-1][j] + s[i][j-1]; 47 } else { 48 s[i][j] = 0; 49 } 50 } 51 } 52 return s[row-1][col-1]; 53 }