- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathSubsetCount.java
77 lines (74 loc) · 2.8 KB
/
SubsetCount.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
77
packagecom.thealgorithms.dynamicprogramming;
/**
* Find the number of subsets present in the given array with a sum equal to target.
* Based on Solution discussed on
* <a href="https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k">StackOverflow</a>
* @author <a href="https://github.com/samratpodder">Samrat Podder</a>
*/
publicfinalclassSubsetCount {
privateSubsetCount() {
}
/**
* Dynamic Programming Implementation.
* Method to find out the number of subsets present in the given array with a sum equal to
* target. Time Complexity is O(n*target) and Space Complexity is O(n*target)
* @param arr is the input array on which subsets are to searched
* @param target is the sum of each element of the subset taken together
*
*/
publicstaticintgetCount(int[] arr, inttarget) {
/*
* Base Cases - If target becomes zero, we have reached the required sum for the subset
* If we reach the end of the array arr then, either if target==arr[end], then we add one to
* the final count Otherwise we add 0 to the final count
*/
intn = arr.length;
int[][] dp = newint[n][target + 1];
for (inti = 0; i < n; i++) {
dp[i][0] = 1;
}
if (arr[0] <= target) {
dp[0][arr[0]] = 1;
}
for (intt = 1; t <= target; t++) {
for (intidx = 1; idx < n; idx++) {
intnotpick = dp[idx - 1][t];
intpick = 0;
if (arr[idx] <= t) {
pick += dp[idx - 1][target - t];
}
dp[idx][target] = pick + notpick;
}
}
returndp[n - 1][target];
}
/**
* This Method is a Space Optimized version of the getCount(int[], int) method and solves the
* same problem This approach is a bit better in terms of Space Used Time Complexity is
* O(n*target) and Space Complexity is O(target)
* @param arr is the input array on which subsets are to searched
* @param target is the sum of each element of the subset taken together
*/
publicstaticintgetCountSO(int[] arr, inttarget) {
intn = arr.length;
int[] prev = newint[target + 1];
prev[0] = 1;
if (arr[0] <= target) {
prev[arr[0]] = 1;
}
for (intind = 1; ind < n; ind++) {
int[] cur = newint[target + 1];
cur[0] = 1;
for (intt = 1; t <= target; t++) {
intnotTaken = prev[t];
inttaken = 0;
if (arr[ind] <= t) {
taken = prev[t - arr[ind]];
}
cur[t] = notTaken + taken;
}
prev = cur;
}
returnprev[target];
}
}