Sum of SubSets (java)
Mon Nov 18 2024 07:30:21 GMT+0000 (Coordinated Universal Time)
Saved by @signup1
import java.util.*; public class SumOfSubsets { // Function to find all subsets whose sum equals the target sum public static void findSubsets(int[] set, int n, int targetSum) { List<Integer> currentSubset = new ArrayList<>(); backtrack(set, n, targetSum, 0, currentSubset); } // Backtracking function to find the subsets private static void backtrack(int[] set, int n, int targetSum, int index, List<Integer> currentSubset) { // Base case: if we've considered all elements if (index == n) { int sum = 0; for (int num : currentSubset) { sum += num; } // If the sum of the current subset equals the target, print it if (sum == targetSum) { System.out.println(currentSubset); } return; } // Include the current element currentSubset.add(set[index]); // Recur with the element included backtrack(set, n, targetSum, index + 1, currentSubset); // Exclude the current element currentSubset.remove(currentSubset.size() - 1); // Recur with the element excluded backtrack(set, n, targetSum, index + 1, currentSubset); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the number of elements in the set and the target sum 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(); // Find and print the subsets whose sum equals the target sum System.out.println("Subsets whose sum equals " + targetSum + ":"); findSubsets(set, n, targetSum); scanner.close(); } }
Comments