LeetCode: Unique Paths

LeetCode: Unique Paths

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class UniquePaths {
public int uniquePaths1(int m, int n) {
if (m < 1 || n < 1) {
return 0;
}
if (m == 1) {
return 1;
}
if (n == 1) {
return 1;
}
return uniquePaths1(m - 1, n) + uniquePaths1(m, n - 1);
}
public int uniquePaths2(int m, int n) {
if (m < 1 || n < 1) {
return 0;
}
if (m == 1 || n == 1) {
return 1;
}
int[][] result = new int[m][n];
for (int i = 0; i < m; i++) {
result[i][0] = 1;
}
for (int i = 0; i < n; i++) {
result[0][i] = 1;
}
for(int i =1; i< m; i++) {
for(int j = 1; j < n; j++) {
result[i][j] = result[i][j-1] + result[i-1][j];
}
}
return result[m-1][n-1];
}
}