https://leetcode.com/problems/unique-paths/

1. recursion:

  1. class Solution(object):
  2. def uniquePaths(self, m, n):
  3. """
  4. :type m: int
  5. :type n: int
  6. :rtype: int
  7. """
  8. if m==1 or n==1:
  9. return 1
  10. return self.uniquePaths(m - 1, n) + self.uniquePaths(m, n - 1)

2. dynamic programming:

  1. class Solution(object):
  2. def uniquePaths(self, m, n):
  3. """
  4. :type m: int
  5. :type n: int
  6. :rtype: int
  7. """
  8. # set up a m*n matrix, all values are 1
  9. d = [([1] * n) for _ in range(m)]
  10. # The number in the matrix represents
  11. # the number of paths that could reach the current one for top-left
  12. #
  13. # Also, the one instead of in the 1st row or 1st column are sum of its left one and its upper one
  14. #
  15. # for example, m = 3, n = 4
  16. # d = 1 1 1 1
  17. # 1 1 1 1
  18. # 1 1 1 1
  19. # -->
  20. # d = 1 1 1 1
  21. # 1 2 3 4
  22. # 1 3 6 10
  23. for col in range(1, m):
  24. for row in range(1, n):
  25. d[col][row] = d[col - 1][row] + d[col][row - 1]
  26. return d[m - 1][n - 1]