What technique do I use for when I want to check all possible combinations of a set?

后端 未结 9 2067
既然无缘
既然无缘 2021-01-18 23:38

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.

9条回答
  •  再見小時候
    2021-01-19 00:05

    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 } })

提交回复
热议问题