I\'m working through an interview question that goes like:
Given an array of integers and sum, check whether any combination adds up to the sum.>
Some care with terminology is needed here. Combinations is used to refer to picking k
items from a set of n
items, where the order of the k
items does not matter. The related concept of picking k
items from a set of n
items, where the order of the k
items does matter, is referred to as a permutation.
What you initially talk about, however:
Given an array of integers and sum, check whether any combination adds up to the sum.
is a different thing - here there is no fixed k
: you are interested in any size subset of the original items.
The set of all subsets of a set S is called the power-set of S, and there is a very simple formula for the number of members it contains. I will leave that as an exercise - once you have worked it out, it should be relatively obvious how to enumerate through the members of a set's powerset.
(Hint: the power-set of { 1, 2 }
is { {}, { 1 }, { 2 }, { 1, 2 } }
)