Lets say we have the string aabc
. If you take two chars from this string without replacement, your result will be in the set {aa, ab, ac, bc}
.
I'm trying to develop an algorithm to construct this set. It's important that there be no duplicates. The algorithm if all chars are unique is simple, but it gets more complicated if there are duplicates. I came up with this, but I'm curious if there are simpler solutions:
from collections import Counter
class Solution(object):
def combinations(self, s, k):
s = Counter(s)
self.res = []
self.combo_helper('', s, k)
return self.res
def combo_helper(self, used, remaining, k):
if k == 0:
self.res.append(used)
else:
new = remaining.copy()
for n in remaining:
if remaining[n]:
new[n] -= 1
self.combo_helper(
used+n, new, k-1
)
new = new.copy()
new[n] = 0