-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCodeQ62.java
More file actions
61 lines (54 loc) · 1.7 KB
/
leetCodeQ62.java
File metadata and controls
61 lines (54 loc) · 1.7 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package DynamicProgramming;
public class leetCodeQ62 {
public static void main(String[] args) {
int m = 3 ;
int n = 7 ;
int[][] dp = new int[m][n];
// Tabulation S.C = O(m*n)
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0)
dp[i][j] = 1;
else
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
System.out.println(dp[m - 1][n - 1]);
// Tabulation Optimized S.C = O(n)
int[][] dp1 = new int[2][n];
for (int j = 0; j < n; j++) {
dp1[0][j] = 1;
dp1[1][j] = 1;
}
for (int i = 1; i <= m - 1; i++) { // m-1 times ;
// DP wala kaam
for (int j = 1; j < n; j++) {
dp1[1][j] = dp1[1][j - 1] + dp1[0][j];
}
// copy the first row to 0th row
for (int j = 1; j < n; j++) {
dp1[0][j] = dp[1][j];
}
}
System.out.println(dp1[1][n-1]);
// Tabulation Optimised S.C = O(n)
// Without Copy Pasting
for (int j = 0; j < n; j++) {
dp1[0][j] = 1;
dp1[1][j] = 1;
}
for (int i = 1; i <= m - 1; i++) { // m-1 times ;
if (i % 2 == 1) {
for (int j = 1; j < n; j++) {
dp1[1][j] = dp1[1][j - 1] + dp1[0][j];
}
}
else {
for (int j = 1; j < n; j++) {
dp1[0][j] = dp1[0][j - 1] + dp1[1][j];
}
}
}
System.out.println(Math.max(dp1[1][n - 1], dp1[0][n - 1]));
}
}