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(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter