-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniquePaths.java
More file actions
41 lines (32 loc) · 848 Bytes
/
UniquePaths.java
File metadata and controls
41 lines (32 loc) · 848 Bytes
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
36
37
38
39
40
41
package org.sean.recursive;
import java.util.Arrays;
/***
* 62. Unique Paths
*/
public class UniquePaths {
private int[][] cache;
public int uniquePaths(int m, int n) {
if(cache == null) {
cache = new int[m][n];
for(int i = 0; i < m; i++) {
Arrays.fill(cache[i], -1);
}
}
if(m >= 1 && n >= 1 && cache[m -1][n - 1] >= 0) {
return cache[m -1][n - 1];
}
if(m <= 0 || n <= 0)
return 0;
if(m == 1 && n == 1)
return 1;
int up = uniquePaths(m -1, n);
int left = uniquePaths(m, n - 1);
if(m - 1 > 0 && n > 0) {
cache[m - 2][n - 1] = up;
}
if(m > 0 && n - 1 > 0) {
cache[m - 1][n - 2] = left;
}
return up + left;
}
}