Unique paths#

Levels: level-4
Data structures: array
Algorithms: dynamic-programming

LeetCode

Description#

  • A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
  • The robot can only move either down or right at any point in time.
  • The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
  • How many possible unique paths are there?

Examples#

1Input: m = 3, n = 2
2Output: 3
3Explanation:
4From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
51. Right -> Right -> Down
62. Right -> Down -> Right
73. Down -> Right -> Right
1Input: m = 7, n = 3
2Output: 28

Constraints:

  • 1 <= m, n <= 100
  • It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

Python Solution#

1class Solution:
2    # @return an integer
3    def uniquePaths(self, m, n):
4        aux = [[1 for x in range(n)] for x in range(m)]
5        for i in range(1, m):
6            for j in range(1, n):
7                aux[i][j] = aux[i][j - 1] + aux[i - 1][j]
8        return aux[-1][-1]