How to generate combinations of K
elements chosen from the set of size N
where some elements are duplicates? For example:
[1, 1, 2, 3, 3, 3] choosing subsets of size 3 we have: [1, 1, 2] [1, 1, 3] [1, 2, 3] [1, 3, 3] [2, 3, 3] [3, 3, 3]
Somewhat clumsy algorithm could be derived from simple generation of combinations without repetitions — however its "clumsiness" make me hesitating and I'm interested whether more nice approach exists. Regretfully "Combinations with Repetitions" on the web mostly refer to another problem (if I got it right) where the number of repetitions for each element is unbounded.
Thanks in advance for hints / links!
Why not to use bitmasks?
Easily you can generate all possible subsets and work only with the subsets containing exactly k elements.
If you don't want to generate unnecessary subsets, I provide you a nice code I found in topcoder forums:
next(x) returns the next integer > x with the same number of bits turned on in O(logN).
ur problem can be reduced to the following:
given a vector (a1, a2, ... an), find the number of vectors (b1, b2, ... bn) such that:
on hindsight this looks to be solvable using dynamic programming, but i'm not very sure.
Use backtracking, with an element, decide how many will it be appeared.
Call backtrack(1, 1). All arrays above are one-based.