62 Unique Paths
A robot is located at the top-left corner of a_m_x_n_grid (marked 'Start' in the diagram below).
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 (marked 'Finish' in the diagram below).
How many possible unique paths are there?
three ways credit to youtube edward shi
- [x] Basic Dynamic Programming, time O(m * n), space O(m * n)
- [x] Dynamic Programming, space O(n)
- [x] combination (m,n) m = m + n - 2, n = m - 1
class Solution {
public int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0) {
return 0;
}
int[][] path = new int[m][n];
for (int i = 0; i < m; i++) {
path[i][0] = 1;
}
for (int i = 0; i < n; i++) {
path[0][i] = 1;
}
for (int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
path[i][j] = path[i-1][j] + path[i][j-1];
}
}
return path[m-1][n-1];
}
}
class Solution {
public int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0) {
return 0;
}
int[] res = new int[n];
res[0] = 1;
for (int i = 0; i < m ; i++) {
for (int j = 1; j < n; j++) {
res[j] = res[j] + res[j - 1];
}
}
return res[n - 1];
}
}
class Solution {
public int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0) {
return 0;
}
double res = 1;
int count = m + n - 2;
int k = m - 1;
for (int i = 1; i <= k; i++) {
res = res * (count - k + i) / i;
}
return (int)res;
}
}