Here shows 3 Approaches to slove this problem: Dynamic Programming, Recursion, Math.
Dynamic Programming
The equation is: f(i,j)=f(i−1,j)+f(i,j−1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicintuniquePaths(int m, int n){ int[][] dp = newint[m][n];
for (int i = 0; i < n; i++) { dp[0][i] = 1; }
for (int i = 0; i < m; i++) { dp[i][0] = 1; }
for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = Math.max(dp[i][j - 1] + 1, dp[i][j - 1] + dp[i - 1][j]); } }
return dp[m - 1][n - 1]; }
Analysis
Time Complexity: O(mn)
Space Complexity: O(mn)
Recursion
The DFS is top-down dynamic programming with memoization. If we do ordinary DFS without proper memoization, it will have a TLE error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicintuniquePaths(int m, int n){ return dfs(new HashMap<Pair, Integer>(), 0, 0, m, n); }
privatestaticintdfs(Map<Pair, Integer> cache, int r, int c, int rows, int cols){ Pair p = new Pair(r, c);
if (cache.containsKey(p)) { return cache.get(p); }
if (r == rows - 1 || c == cols - 1) { return1; } cache.put(p, dfs(cache, r + 1, c, rows, cols) + dfs(cache, r, c + 1, rows, cols)); return cache.get(p); }
Analysis
Time Complexity: O(mn)
Space Complexity: O(mn)
Combination Math
In the process from the top left to the bottom right, we need to move m+n−2 steps, of which there are m−1 moves down and n−1 times to the right.
Therefore, the total number of paths is equal to the number of options for selecting m−1 downward moves from m+n−2 moves, that is, the number of combinations: