Link: 62. Unique Paths - Medium
Track: Amazon Tag
Question
Restate
Edge Case
m = 1, n = 1, return 1
Method 1 - DP
Method 2
Method 1 - DP
Approach
Define dp[r][c] = number of ways to reach cell (r,c) from (0,0).
To arrive at (r,c), the last move must be:
-
from top
(r-1,c)(move down), or -
from left
(r,c-1)(move right) -
Q: Why start from 1?
-
Row 0 and col 0 are base cases (only 1 way), so we start filling from (1,1).
Complexity
- Time Complexity: O()
- Space Complexity: O()
Code
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
rows, cols = m, n
dp = [[1] * cols for _ in range(rows)]
for row in range(1, rows):
for col in range(1, cols):
print(row, col)
dp[row][col] = dp[row - 1][col] + dp[row][col - 1]
return dp[rows-1][cols-1]History
- Feb-19-2026 Peeked