import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter the target sum:");
int target = sc.nextInt();
System.out.println("Subsets with sum equal to " + target + " are:");
findSubsets(arr, n, target);
sc.close();
}
private static void findSubsets(int[] arr, int n, int target) {
List<Integer> currentSubset = new ArrayList<>();
subsetSumHelper(arr, n, 0, 0, target, currentSubset);
}
private static void subsetSumHelper(int[] arr, int n, int index, int currentSum, int target, List<Integer> currentSubset) {
if (currentSum == target) {
System.out.println(currentSubset);
return;
}
if (index >= n || currentSum > target) {
return;
}
currentSubset.add(arr[index]);
subsetSumHelper(arr, n, index + 1, currentSum + arr[index], target, currentSubset);
currentSubset.remove(currentSubset.size() - 1);
subsetSumHelper(arr, n, index + 1, currentSum, target, currentSubset);
}
}
Comments