To solve the problem of finding the number of unique paths from the top-left corner to the bottom-right corner of an (m \times n) grid (moving only right or down), we can use dynamic programming with optimized space complexity.
Approach
The key insight here is that the number of ways to reach a cell ((i, j)) is the sum of the ways to reach the cell above it ((i-1, j)) and the cell to the left of it ((i, j-1)). This is because you can only move right or down.
-
Base Cases:
- The first row: All cells can only be reached by moving right, so there's exactly 1 way to reach each cell.
- The first column: All cells can only be reached by moving down, so there's exactly 1 way to reach each cell.
-
Dynamic Programming Optimization:
- Instead of using a 2D array, we use a 1D array to save space. For each row, we update the array to reflect the number of ways to reach each cell in the current row. This works because we only need the previous row's values (for the cell above) and the current row's previous values (for the cell to the left).
Solution Code
def uniquePaths(m, n):
dp = [1] * n # Initialize first row (all 1s)
for i in range(1, m):
for j in range(1, n):
dp[j] += dp[j-1] # Update current cell with sum of left and above
return dp[-1] # The last element is the number of paths to the bottom-right corner
Explanation
- Initialization: The array
dpstarts with all 1s, representing the first row (each cell has exactly one path from the top-left corner). - Row-wise Update: For each subsequent row, we iterate through the columns. For each cell ((i, j)), we add the value of the cell to the left ((dp[j-1])) to the current value of (dp[j]) (which holds the value from the row above).
- Result: The last element of the
dparray gives the number of unique paths to the bottom-right corner of the grid.
This approach has a time complexity of (O(m \times n)) (since we iterate over each cell once) and a space complexity of (O(n)) (using a 1D array instead of a 2D array). This is efficient and optimal for the problem.
Example: For (m=3, n=7), the output is 28, which is the number of unique paths from the top-left to the bottom-right corner. This is calculated as (\binom{3+7-2}{3-1} = \binom{8}{2} = 28), which aligns with the DP result.
Another example: For (m=2, n=2), the output is 2 (right then down, or down then right).
This solution is both efficient and easy to understand, making it suitable for the problem constraints.


作者声明:本文包含人工智能生成内容。