generate all subsets of size k from a set

后端 未结 9 1355
南旧
南旧 2020-12-08 03:30

I want to generate all the subsets of size k from a set.

eg:-say I have a set of 6 elements, I have to list all the subsets in which the cardinality of elements is 3

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 04:18

    The most intuitive algorithm would indeed use recursion. When you have a set, we will assume you can iterate over all its elements.

    If I call tail(e) a set of all the elements after element e.

    Thus I want right now combinations(s,k)

    loop over each element in s and get e :: combinations(tail(e), k-1) where :: means "concatenated to each of"

    Of course sometimes there will be no such combinations (you are off the end of the list).

    You just need a master collection (set of sets) to add your combinations to and a way to create

    So assuming we have no globals anywhere we can have something like:

    getCombinations( headset [in], tailset [in], count [in], output [append] )
    

    headset or tailset could be empty. count could be 0, in which case we write "headset" to output (the base condition) otherwise we iterate through each element in tailset, adding it (locally) to headset, make tailset (locally) the tail of our element, subtract 1 from count and "recurse" by calling the function.

提交回复
热议问题