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.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d1-1-data-1.txt

5
3 1 4 2 5
6
What your program must print for d1-1-data-1.txt
[3, 1, 2]
[1, 5]
[4, 2]
Found: 3

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d1-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d1-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.