-
Notifications
You must be signed in to change notification settings - Fork 820
/
HandshakesThatDontCross.java
64 lines (59 loc) · 1.76 KB
/
HandshakesThatDontCross.java
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
62
63
64
/* (C) 2024 YourCompanyName */
package dynamic_programming;
import java.util.Arrays;
/**
* Created by gouthamvidyapradhan on 19/02/2020 You are given an even number of people num_people
* that stand around a circle and each person shakes hands with someone else, so that there are
* num_people / 2 handshakes total.
*
* <p>Return the number of ways these handshakes could occur such that none of the handshakes cross.
*
* <p>Since this number could be very big, return the answer mod 10^9 + 7
*
* <p>Example 1:
*
* <p>Input: num_people = 2 Output: 1 Example 2:
*
* <p>Input: num_people = 4 Output: 2 Explanation: There are two ways to do it, the first way is
* [(1,2),(3,4)] and the second one is [(2,3),(4,1)]. Example 3:
*
* <p>Input: num_people = 6 Output: 5 Example 4:
*
* <p>Input: num_people = 8 Output: 14
*
* <p>Constraints:
*
* <p>2 <= num_people <= 1000 num_people % 2 == 0
*/
public class HandshakesThatDontCross {
public static void main(String[] args) {
System.out.println(new HandshakesThatDontCross().numberOfWays(20));
}
int[] DP;
final int MOD = 1000000007;
public int numberOfWays(int N) {
// DP = new int[N + 1][N + 1];
DP = new int[N + 1];
Arrays.fill(DP, -1);
//
// for(int i = 0; i <= N; i ++){
// Arrays.fill(DP[i], -1);
// }
return dp(0, N - 1);
}
private int dp(int i, int j) {
if (i > j) return 1;
else if ((j - i + 1) % 2 != 0) return 0;
else if (DP[j - i + 1] != -1) return DP[j - i + 1];
else {
int sum = 0;
for (int k = i; k <= j; k++) {
int left = (dp(i + 1, k - 1) % MOD);
int right = (dp(k + 1, j) % MOD);
sum = ((sum + ((left * right) % MOD)) % MOD);
}
DP[j - i + 1] = sum;
return sum;
}
}
}