recursively find subsets

后端 未结 4 1183
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 10:37

Here is a recursive function that I\'m trying to create that finds all the subsets passed in an STL set. the two params are an STL set to search for subjects, and a number i >=

4条回答
  •  失恋的感觉
    2021-01-26 11:06

    From what I understand you are actually trying to generate all subsets of 'i' elements from a given set right ?

    Modifying the input set is going to get you into trouble, you'd be better off not modifying it.

    I think that the idea is simple enough, though I would say that you got it backwards. Since it looks like homework, i won't give you a C++ algorithm ;)

    generate_subsets(set, sizeOfSubsets) # I assume sizeOfSubsets cannot be negative
                                         # use a type that enforces this for god's sake!
      if sizeOfSubsets is 0 then return {}
      else if sizeOfSubsets is 1 then
        result = []
        for each element in set do result <- result + {element}
        return result
      else
        result = []
        baseSubsets = generate_subsets(set, sizeOfSubsets - 1)
        for each subset in baseSubssets
          for each element in set
            if no element in subset then result <- result + { subset + element }
        return result
    

    The key points are:

    • generate the subsets of lower rank first, as you'll have to iterate over them
    • don't try to insert an element in a subset if it already is, it would give you a subset of incorrect size

    Now, you'll have to understand this and transpose it to 'real' code.

提交回复
热议问题