1
1
package com .thealgorithms .dynamicprogramming ;
2
2
3
+ /**
4
+ * A utility class that contains the Sum of Subset problem solution using
5
+ * recursion.
6
+ *
7
+ * The Sum of Subset problem determines whether a subset of elements from a
8
+ * given array sums up to a specific target value.
9
+ *
10
+ * Wikipedia: https://en.wikipedia.org/wiki/Subset_sum_problem
11
+ */
3
12
public final class SumOfSubset {
13
+
4
14
private SumOfSubset () {
5
15
}
6
16
17
+ /**
18
+ * Determines if there exists a subset of elements in the array `arr` that
19
+ * adds up to the given `key` value using recursion.
20
+ *
21
+ * @param arr The array of integers.
22
+ * @param num The index of the current element being considered.
23
+ * @param key The target sum we are trying to achieve.
24
+ * @return true if a subset of `arr` adds up to `key`, false otherwise.
25
+ *
26
+ * This is a recursive solution that checks for two possibilities at
27
+ * each step:
28
+ * 1. Include the current element in the subset and check if the
29
+ * remaining elements can sum up to the remaining target.
30
+ * 2. Exclude the current element and check if the remaining elements
31
+ * can sum up to the target without this element.
32
+ */
7
33
public static boolean subsetSum (int [] arr , int num , int key ) {
8
34
if (key == 0 ) {
9
35
return true ;
@@ -14,7 +40,6 @@ public static boolean subsetSum(int[] arr, int num, int key) {
14
40
15
41
boolean include = subsetSum (arr , num - 1 , key - arr [num ]);
16
42
boolean exclude = subsetSum (arr , num - 1 , key );
17
-
18
43
return include || exclude ;
19
44
}
20
45
}
0 commit comments