views:

104

answers:

1

Write a program which, given a list of up to 10 integer numbers and a sum, will display a subset of the numbers whose total is that sum if one exists or indicate that none exists otherwise. For example, for the list: 5,13,24,9,3,3 and sum = 28, your program should display 13, 9, 3, 3.

How to do this in C++ using a recursive function?

+1  A: 

A recursive function isn't actually the simplest or fastest way to do this, but you can write a function that takes the desired sum and a list of integers.

The function goes through the list one element at a time, and for each element it subtracts it from the current goal value, and recursively calls itself with the new goal and a new list with the currently subtracted element removed. The base case is an empty list and a value. If that value is zero, return true, else return false. Whenever the function returns true, the currently considered element is a value in the solution, so you can output it.

swestrup