Search and backtracking · 9 / 15 Exercise Hard

Subsets with a target sum

Objective

Create a Python program that finds all the subsets of a list whose sum is a given value, with backtracking and pruning: a branch is abandoned as soon as it cannot reach the sum.

Instructions

  • Read a line with positive integers separated by spaces (at most 10) and then a line with the target (a positive integer).
  • Write a recursive function search(values, i, remaining, current, solutions). If remaining is 0, store a solution and return. If there are no elements left or remaining is negative, simply return (pruning). Otherwise, first try including element i (and remove it when coming back) and then try without it.
  • Show each solution on a line with the format 2 + 3 + 5 = 10, in the order they are found, and finish with Solutions: k.
Input
3 34 4 12 5 2
9
Output
3 + 4 + 2 = 9
4 + 5 = 9
Solutions: 2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise