Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Unique Paths

The problem description can be found in LeetCode.

Approach

The robot can move either down or right, which means that we have a kind of decision tree: at every step we can take one of the two directions.

Let's derive a partial space tree by first going down and then right:

example000, 0l_101, 000--l_10r_010, 100--r_01l_202, 0l_10--l_20l_303, 0l_20--l_30l_212, 1l_20--l_21l_222, 2l_21--l_22r_111, 1r_01--r_11r_212, 1r_11--r_21

Where we marked the following:

  • Red: invalid coordinates.
  • Blue: the repeated work for the coordinate (2, 1).
  • Green: a valid solution.

Since we have some repeated work, we can use memoization to store some already calculated results.

Solution

from typing import Dict, Tuple


class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        def dfs(row: int, col: int, memo: Dict[Tuple[int, int], int]):
            if (row, col) in memo:
                return memo[(row, col)]
            if row == m - 1 and col == n - 1:
                return 1
            if not (0 <= row < m) or not (0 <= col < n):
                return 0

            ans = 0
            ans += dfs(row + 1, col, memo)
            ans += dfs(row, col + 1, memo)

            memo[(row, col)] = ans

            return ans

        return dfs(0, 0, {})

Complexity

  • Time:
  • Space:

Where and are the two inputs of the function.