[LintCode] Unique Paths
A robot is located at the top-left corner of a m x n grid.
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
m and n will be at most 100.
Given m = 3
and n = 3
, return 6
.
Given m = 4
and n = 5
, return 35
.
Solution 1. Recursion
at any given point (x, y), f(x, y) = f(x + 1, y) + f(x, y + 1), we can form a dfs recursive solution using this formula.
This recursive solution has overlapping problems.
pathsTo(m, n) = pathsTo(m - 1, n) + pathsTo(m, n - 1);
pathsTo(m - 1, n) = pathsTo(m - 2, n) + pathsTo(m - 1, n - 1);
pathsTo(m, n - 1) = pathsTo(m, n - 2) + pathsTo(m - 1, n - 1);
1 public class Solution { 2 private int paths = 0; 3 public int uniquePaths(int m, int n) { 4 dfs(m - 1, n - 1, 0, 0); 5 return paths; 6 } 7 private void dfs(int dstX, int dstY, int currX, int currY){ 8 if(currX == dstX && currY == dstY){ 9 paths++; 10 return; 11 } 12 if(currX > dstX || currY > dstY){ 13 return; 14 } 15 dfs(dstX, dstY, currX + 1, currY); 16 dfs(dstX, dstY, currX, currY + 1); 17 } 18 }
Solution 2. Dynamic Programming, O(m * n) runtime, O(m * n) space
State: f[i][j] : the number of different paths from (0, 0) to (i, j)
Function: f[i][j] = f[i][j - 1] + f[i - 1][j];
Initialization: f[i][0] = 1, f[0][j] = 1.
Answer: f[m - 1][n - 1]
1 public class Solution { 2 public int uniquePaths(int m, int n) { 3 int[][] f = new int[m][n]; 4 f[0][0] = 1; 5 for(int i = 1; i < m; i++){ 6 f[i][0] = 1; 7 } 8 for(int j = 1; j < n; j++){ 9 f[0][j] = 1; 10 } 11 for(int i = 1; i < m; i++){ 12 for(int j = 1; j < n; j++){ 13 f[i][j] = f[i][j - 1] + f[i - 1][j]; 14 } 15 } 16 return f[m - 1][n - 1]; 17 } 18 }
Solution 3. Dynamic Programming with space optimization, O(m * n) runtime, O(n) space
Based on the state function, we know that to compute the current row's results, we only need the results from the previous and the current rows. So we can use rolling array to optimize the space complexity to O(n).
1 public class Solution { 2 public int uniquePaths(int m, int n) { 3 int[][] T = new int[2][n]; 4 for(int j = 0; j < n; j++) { 5 T[0][j] = 1; 6 } 7 for(int i = 1; i < m; i++) { 8 T[i % 2][0] = 1; 9 for(int j = 1; j < n; j++) { 10 T[i % 2][j] = T[i % 2][j - 1] + T[(i - 1) % 2][j]; 11 } 12 } 13 return T[(m - 1) % 2][n - 1]; 14 } 15 }
Related Problems
Unique Paths II
Unique Paths III