11from typing import Dict , Tuple
2-
2+ from functools import lru_cache
33
44def unique_paths_math (m : int , n : int ) -> int :
55 """Uses math formula"""
@@ -28,6 +28,7 @@ def unique_paths_top_down(m: int, n: int) -> int:
2828 """
2929 cache : Dict [Tuple [int , int ], int ] = {}
3030
31+ @lru_cache (None )
3132 def unique_path_helper (row : int , col : int ) -> int :
3233 # If already calculated, re-use those
3334 if (row , col ) in cache :
@@ -48,28 +49,30 @@ def unique_path_helper(row: int, col: int) -> int:
4849 return unique_path_helper (m , n )
4950
5051
51- def unique_paths_bottom_up (m : int , n : int ) -> int :
52+ def unique_paths_bottom_up (rows : int , cols : int ) -> int :
5253 """Uses bottom-up approach
5354
54- Complexity Analysis:
55- - Time Complexity: O(m*n)
56- - Space Complexity: O(n)
55+ Complexity Analysis
56+
57+ Time Complexity: O(m * n) where m and n are the dimensions of the grid. For both the recursive and iterative
58+ solutions, we need to fill in a table of size m x n.
59+
60+ Space Complexity: O(m * n) where m and n are the dimensions of the grid. The recursive solution uses O(m * n) space
61+ due to the call stack, while the iterative solution uses O(m * n) space for the dp table.
5762 """
58- row = [1 ] * n
63+ dp = [[ 0 ] * cols for _ in range ( rows )]
5964
60- # go through all rows except the last one
61- for i in range (m - 1 ):
62- new_row = [ 1 ] * n
65+ # Set base case: there is only one way to reach any cell in the first row (moving only right)
66+ for r in range (cols ):
67+ dp [ 0 ][ r ] = 1
6368
64- # go through every column except the right most column
65- # because the last value in every row is 1
66- # start at second to last position and
67- # keep going until we get to the beginning (reverse order)
69+ # Set base case: there is only one way to reach any cell in the first column (moving only down)
70+ for r in range (rows ):
71+ dp [r ][0 ] = 1
6872
69- for j in range (n - 2 , - 1 , - 1 ):
70- # right value + value below
71- new_row [j ] = new_row [j + 1 ] + row [j ]
72- # update the row
73- row = new_row
73+ # Fill in the rest of the table
74+ for i in range (1 , rows ):
75+ for j in range (1 , cols ):
76+ dp [i ][j ] = dp [i - 1 ][j ] + dp [i ][j - 1 ]
7477
75- return row [ 0 ]
78+ return dp [ rows - 1 ][ cols - 1 ]
0 commit comments