Thursday, October 26, 2017

combinations with duplicates

For aaaa,
a
aa
aaa
aaaa

a               a
    a           aa
        a       aaa
            a   aaaa
        a X
    a X
    a X
a X
a X
a X

For aaab,
a
aa
aaa
ab
aab
aaab
b

a               a
    a           aa
        a       aaa
            b   aaab
        b       aab
    a X         aa      X
        b       aab     X
    b           ab
a X             a       X
    a           aa      X
        b       aab     X
    b           ab      X
a X             a       X
    b           ab      X
b               b
Sort the characters in s so dupes are adjacent to each. The 1st iteration needs to go through and skip the 2nd iteration onward for dupes.
// in is sorted
combineWithDupes(in, start = 0, buffer, items)
    if start > 0:
        items.add(buffer.toString())
    for i = start, i < in.length(), i++:
        if i > start && a[i-1] == a[i]:
            continue
        buffer.append(in[i])
        combineWithDupes(in, i +1, buffer, items)`
        buffer.removeLast()
Bottom-up:
// in is sorted
[] combineWithDupes(in, i = 0)
    if i == in.length():
        yield break
    ch = in[i]
    childitems = combineWithDupes(in, i +1)
    yield ch                                    // a
    for child in childitems:                    // a, aa
        yield ch + child                        // aa, aaa
    if i +1 < in.length() && in[i] == in[i +1]:
        yield break
    for child in childitems:                    // a, aa
        yield child                             // a, aa

No comments:

Post a Comment