image.png

解决思路

排列组合

image.png

动态规划

image.png

  1. public int uniquePaths(int m, int n) {
  2. int[][] dp = new int[m][n];
  3. for (int i = 0;i < m;i++)
  4. dp[i][0] = 1;
  5. for (int j = 0;j < n;j++)
  6. dp[0][j] = 1;
  7. for (int i = 1;i < m;i++){
  8. for (int j = 1;j < n;j++){
  9. dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
  10. }
  11. }
  12. return dp[m - 1][n - 1];
  13. }

优化2:空间复杂度 O(n)

  1. public int uniquePaths(int m, int n) {
  2. int[] cur = new int[n];
  3. Arrays.fill(cur,1);
  4. for (int i = 1; i < m;i++){
  5. for (int j = 1; j < n; j++){
  6. cur[j] += cur[j-1] ;
  7. }
  8. }
  9. return cur[n-1];
  10. }