11package com .thealgorithms .dynamicprogramming ;
22
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+ */
312public final class SumOfSubset {
13+
414 private SumOfSubset () {
515 }
616
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+ */
733 public static boolean subsetSum (int [] arr , int num , int key ) {
834 if (key == 0 ) {
935 return true ;
@@ -14,7 +40,6 @@ public static boolean subsetSum(int[] arr, int num, int key) {
1440
1541 boolean include = subsetSum (arr , num - 1 , key - arr [num ]);
1642 boolean exclude = subsetSum (arr , num - 1 , key );
17-
1843 return include || exclude ;
1944 }
2045}
0 commit comments