Wednesday, March 2, 2022

Target sum subsets

I/P: [10, 20, 30, 40, 50]

60


O/P:

10, 20, 30, . 10, 50, . 20, 40, .




1. We pass the following arguments as parameters to the given function "PrintTarget SumSubsets" : given input array, the index we are at i.e. 0 , initial empty subset, sum of that subset and the target . 

2. BASE CASE: We check whether the index is equal to array of length because it would tell us whether all the elements have been used up or not. 

*NOTE: Here we check condition for arr.length and not arr.length-1 even though the indices start with 0 because when the recursive function is called on the last element it increases the index by 1 for the index arr.length-1 and hence the value stored in "idx" is equal to the arr.length. 

3. We call a recursive function for the YES part of the element. Here, that element gets added to the subset string and arithmetically added to "sos". 

4. Next, we call a recursive function for the NO part of that element. Here, that element does not get added to either the subset string or the "sos". When we run this code it gives us our desired output .


package pep.Day11;

public class TargetSumSubset {
public static void main(String[] args) throws Exception {
int[] arr = {10, 20, 30, 40, 50};
int target = 60;
printTargetSumSubsets(arr, 0, "", 0, target);
}

// set is the subset
// sos is sum of subset
// tar is target
public static void printTargetSumSubsets(int[] arr, int idx, String set, int sos, int tar) {
if (idx == arr.length && sos != tar)
return;
if (sos == tar) {
System.out.println(set+".");
return;
}
printTargetSumSubsets(arr, idx + 1, set + arr[idx] + ", ", sos + arr[idx], tar);
printTargetSumSubsets(arr, idx + 1, set, sos, tar);

}

}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...