LC 62 & LC 63


Solution to LeetCode 62 Unique Paths & LeetCode 63 Unique Paths II .

LeetCode 62

Unique Paths (Medium) [link]

1] Recursion with memoization.

Define f(i,j) as the number of paths from (0,0) to (i,j). There are two ways to reach (i,j): from (i-1,j) or from (i,j-1). The recurrence relation is f(i,j) = f(i-1,j) + f(i,j-1). The base case f(i,0) = 1 because there is only one way from i to 0, same as f(0,j) = 1. The final answer is f(m-1,n-1).

Time complexity O(mn). Space complexity O(mn).

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        # f = [[1 for i in range(n)] for j in range(m)]
        dp = [[1] * n for _ in range(m)]
        for i in range(1,m):
            for j in range(1,n):
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
        return dp[m-1][n-1]

2] Iteration with space optimization. Define f(j) of length n as the number of paths from (0,0) to (i,j). The recurrence relation is f(j) = f(j) + f(j-1). The base case is f(0) = 1. The final answer is f(n-1).

Time complexity O(mn). Space complexity O(n).

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dp = [1] * n
        for i in range(1, m):
            for j in range(1, n):
                dp[j] = dp[j] + dp[j - 1]
        return dp[-1]

LeetCode 63

Unique Paths II (Medium) [link]

If there is obstacle at (i,j), f(i,j) = 0. We need to consider obstacles when constructing base cases as well as iterating dp array.

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m = len(obstacleGrid)
        n = len(obstacleGrid[0])
        dp = [[0] * n for _ in range(m)]
        
        if obstacleGrid[0][0] == 1: return 0
        dp[0][0] = 1
        
        for i in range(1,n):
            if obstacleGrid[0][i] == 0:
                dp[0][i] = dp[0][i-1]

        for j in range(1,m):
            if obstacleGrid[j][0] == 0:
                dp[j][0] = dp[j-1][0]
                
        for i in range(1,m):
            for j in range(1,n):
                if obstacleGrid[i][j] == 0:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]

        return dp[m-1][n-1]

  TOC