-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG.java
76 lines (61 loc) · 2.06 KB
/
GFG.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
65
66
67
68
69
70
71
72
73
74
75
76
//{ Driver Code Starts
// Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int t =
Integer.parseInt(br.readLine().trim()); // Inputting the testcases
while (t-- > 0) {
int N = Integer.parseInt(br.readLine().trim());
int K = Integer.parseInt(br.readLine().trim());
Solution ob = new Solution();
System.out.println(ob.countWaystoDivide(N, K));
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
// Function to count the number
// of ways to divide the number N
// in groups such that each group
// has K number of elements
public int calculate(int pos, int prev, int left, int K, int[][][] dp) {
// Base Case
if (pos == K) {
if (left == 0)
return 1;
else
return 0;
}
// if N is divides completely
// into less than K groups
if (left == 0) return 0;
// If the subproblem has been
// solved, use the value
if (dp[pos][prev][left] != -1) return dp[pos][prev][left];
int answer = 0;
// put all possible values
// greater equal to prev
for (int i = prev; i <= left; i++) {
answer += calculate(pos + 1, i, left - i, K, dp);
}
return dp[pos][prev][left] = answer;
}
// Function to count the number of
// ways to divide the number N in groups
int countWaystoDivide(int N, int K) {
// Intialize DP Table as -1
int dp[][][] = new int[K + 1][N + 1][N + 1];
for (int i = 0; i <= K; i++) {
for (int j = 0; j <= N; j++) {
Arrays.fill(dp[i][j], -1);
}
}
return calculate(0, 1, N, K, dp);
}
};