Algo-Sim › Dynamic Programming
Unique Paths
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Count right/down paths across a grid: each cell is the sum of the cell above and the cell to its left.
Problem
A robot starts in the top-left cell of an m × n grid and can only move right or down. Return how many different paths take it to the bottom-right cell.
Constraints
- 1 ≤ m, n ≤ 100
- The answer is at most 2 · 10⁹
Edge cases to test
- 1 × n or m × 1:
1 - 1 × 1:
1 - Large grids (the count needs 64 bits)
Follow-up questions
- Is there a closed form?
- C(m + n − 2, m − 1): choose which of the moves go down. Compute it step by step to avoid overflow.
- How much space is needed?
- One row:
row[j] += row[j − 1], O(n).
Solution
Java
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int r = 0; r < m; r++) dp[r][0] = 1;
for (int c = 0; c < n; c++) dp[0][c] = 1;
for (int r = 1; r < m; r++) {
for (int c = 1; c < n; c++) {
dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
}
}
return dp[m - 1][n - 1];
}Python
def unique_paths(m, n):
dp = [[0] * n for _ in range(m)]
for r in range(m):
dp[r][0] = 1
for c in range(n):
dp[0][c] = 1
for r in range(1, m):
for c in range(1, n):
dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
return dp[m - 1][n - 1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp = vector<vector<int>>(m, vector<int>(n));
for (int r = 0; r < m; r++)
dp[r][0] = 1;
for (int c = 0; c < n; c++)
dp[0][c] = 1;
for (int r = 1; r < m; r++) {
for (int c = 1; c < n; c++) {
dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
}
}
return dp[m - 1][n - 1];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)