Sum of Subsets
Mon Nov 18 2024 20:35:31 GMT+0000 (Coordinated Universal Time)
Saved by
@hi123
import java.util.*;
public class Main {
private static void sumOfSubSet(int[] set, int n, int targetSum, int index, List<Integer> currentSubset) {
if (index == n) {
int sum = 0;
for (int num : currentSubset) {
sum += num;
}
if (sum == targetSum) {
System.out.println(currentSubset);
}
return;
}
currentSubset.add(set[index]);
sumOfSubSet(set, n, targetSum, index + 1, currentSubset);
currentSubset.remove(currentSubset.size() - 1);
sumOfSubSet(set, n, targetSum, index + 1, currentSubset);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the set: ");
int n = scanner.nextInt();
int[] set = new int[n];
System.out.println("Enter the elements of the set: ");
for (int i = 0; i < n; i++) {
set[i] = scanner.nextInt();
}
System.out.print("Enter the target sum: ");
int targetSum = scanner.nextInt();
System.out.println("Subsets whose sum equals " + targetSum + ":");
List<Integer> currentSubset = new ArrayList<>();
sumOfSubSet(set, n, targetSum, 0, currentSubset);
scanner.close();
}
}
content_copyCOPY
Comments