Skip to content

62. Unique Paths

Problem

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 10**9.

Example 1:

Pasted image 20230903112525.png

Input: m = 3, n = 7
Output: 28

Example 2:

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 -> Down -> Down
  2. Down -> Down -> Right
  3. Down -> Right -> Down

Constraints:

  • 1 <= m, n <= 100

Solve

Dynamic programming

Bottom up loop

We can spot a Recursive formulation, that we can calculate later answer by combining previous result uniquePaths:

uniquePaths(m, n) = uniquePaths(m-1, n) + uniquePaths(m, n-1)

With the most basic answer:

uniquePaths(1, 1) = 1

The final implement:

Time Submitted Status Runtime Memory Language
09/03/2023 11:19 Accepted 38 ms 16.4 MB python3
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        cacheUniquePaths = [[0 for j in range(n+1)] for i in range(m+1)]

        for rowID in range(m):
            for columnID in range(n):
                if rowID == columnID == 0:
                    cacheUniquePaths[0][0] = 1
                    continue

                currentUniquePath = 0

                aboveBlockUniquePath = 0
                if rowID >= 1:
                    aboveBlockUniquePath = cacheUniquePaths[rowID-1][columnID]
                    currentUniquePath += aboveBlockUniquePath

                beforeBlockUniquePath = 0
                if columnID >= 1:
                    beforeBlockUniquePath = cacheUniquePaths[rowID][columnID-1]
                    currentUniquePath += beforeBlockUniquePath

                cacheUniquePaths[rowID][columnID] = currentUniquePath

        return cacheUniquePaths[m-1][n-1]

We can local test using this main function

def test():
    a  = Solution()
    # Example 1:
    m = 3
    n = 7
    result = 28
    out = a.uniquePaths(m,n)
    print("Test 1 is", out == result)
    # Example 2:
    m = 3
    n = 2
    result = 3
    out = a.uniquePaths(m,n)
    print("Test 2 is", out == result)
    # Example 3:
    m = 1
    n = 1
    result = 1
    out = a.uniquePaths(m,n)
    print("Test 3 is", out == result)

if __name__ == "__main__":
    test()

Last update : September 3, 2023
Created : September 3, 2023