dp[c] = 1 initially; for each later row, dp[c] += dp[c − 1] left to right.
Approach 1
import java.util.Arrays;
class Solution {
public int uniquePaths(int m, int n) {
int[] dp = new int[n];
Arrays.fill(dp, 1);
for (int r = 1; r < m; r++)
for (int c = 1; c < n; c++) dp[c] += dp[c - 1];
return dp[n - 1];
}
}
Verdict: Standard.
2
Combinatorics
Time O(min(m, n)) Space O(1)
A path is a sequence of m − 1 downs and n − 1 rights: C(m + n − 2, m − 1). Compute it incrementally with long.
Approach 2
class Solution {
public int uniquePaths(int m, int n) {
long result = 1;
int k = Math.min(m, n) - 1, total = m + n - 2;
for (int i = 1; i <= k; i++) result = result * (total - k + i) / i;
return (int) result;
}
}
Verdict: Fast, but only for the obstacle-free version.
Before you submit
Edge cases and common mistakes
Test these inputs
1 × n or m × 1 (one path)
Mistakes people make
Factorials overflowing (compute the binomial incrementally).