forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnique Paths.java
More file actions
39 lines (31 loc) · 802 Bytes
/
Unique Paths.java
File metadata and controls
39 lines (31 loc) · 802 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
public class Solution {
/**
* Time: O(n*m)
* Memory: O(n*m)
*/
public int uniquePaths(int n, int m) {
int[][] grid = new int[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0 || j == 0) {
grid[i][j] = 1;
} else {
grid[i][j] = grid[i][j - 1] + grid[i - 1][j];
}
}
}
return grid[m - 1][n - 1];
}
}
public class Solution {
/**
* Time: O(min(n,m))
* Memory: O(1)
*/
public int uniquePaths(int n, int m) {
long paths = 1;
for (int i = m + n - 2, j = 1; i >= Math.max(m, n); --i, ++j)
paths = (paths * i) / j;
return (int) paths;
}
}