As far as I understand, are you really trying to generate all subsets of "i" elements from a given set?
Changing the input data set will lead you into trouble; you better not change it.
I think this idea is quite simple, although I would say that you got it back. Since this looks like homework, I will not give you an algorithm in C ++;)
generate_subsets(set, sizeOfSubsets) # I assume sizeOfSubsets cannot be negative # use a type that enforces this for god 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
Key points are:
- generate lower-level subsets first, as you will have to iterate over them
- do not try to insert an element into a subset, if it already exists, it will give you a subset of the wrong size
Now you need to understand this and transfer it to the "real" code.
source share