THINK FIRST·CODE LATER

← All labs

Subsets with a Target Sum

Problem

Write a program that reads n (0 ≤ n ≤ 20), then n positive integers, then a target t (t ≥ 0). Print every subset of the numbers whose sum is exactly t, one per line, then the number of subsets found.

Use backtracking over the indices 0 … n−1. At each index try taking the number first, then leaving it; this fixes the output order. Print each subset with System.out.println(list) on a List<Integer>, so the numbers appear in input order, e.g. [3, 1, 2]. Prune a branch as soon as its running sum exceeds t.

Input:

5
3 1 4 2 5
6

Output:

[3, 1, 2]
[1, 5]
[4, 2]
Found: 3

If no subset works, print only Found: 0. Equal numbers at different positions are different elements (they give separate lines). When t is 0, the empty subset [] is the only answer.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.