The problem to solve
Solve k-combination whose input may contain repeated items, and return only unique combinations.
e.g input is [0,1,2,2,4]
, k = 2
, the result is:
{(0, 1), (2, 4), (1, 2), (0, 4), (1, 4), (0, 2), (2, 2)}
The solution I can think of
The only general solution I can think is to use a set
or map
to extract unique results.
e.g with python
from itertools import combinations
print (set(combinations([0, 1, 2, 2, 4], 2)))
Questions
- Is there a general solution to do this, without using a set/map for filtering.
I can generate combinations of unique items, in order (refer: https://stackoverflow.com/a/76048486), but if there are repeated items, then there will be repeated combinations.
I've read this: https://math.stackexchange.com/a/554237 , seems it says there is no general solution to get all unique combinations, though there do have a formula to get count of unique combinations.
But, I'm not sure.
@Update - Summary & tips
- According to the answers, there are ways both via iteration & recursion to do this.
- When translating from
python
togo
:yield
in python, needchan
in go, or u need return all combinations (which can be huge for large input).- python's
else
forfor
andwhile
is omitted whenbreak
. - list
slicing
in python will make a copy (of reference ?), while slicing a go slice will reuse the same underlying array, (so in go, if the slice being copied will be modified later, and u don't want that change in the copy, then u should copy/append it into a new slice).