I have a string like “0189”, for which I need to generate all subsequences, but the ordering of the individual characters must be kept, i.e, here 9 should not come before 0, 1 or 8. Ex: 0, 018, 01, 09, 0189, 18, 19, 019, etc.
Another example is “10292” for which subsequences would be: 1, 10, 02, 02, 09, 29, 92, etc. As you might have noticed ’02’ two times, since ‘2’ comes twice in the given string. But again things like: 21, 01, 91 are invalid as order is to be maintained.
Any algorithm or psuedo code, which could be implemented in C/C++ would be appreciated!
I’d recommend using the natural correspondence between the power set of a sequence and the set of binary numbers from
0to2^n - 1, wherenis the length of the sequence.In your case,
nis 4, so consider 0 =0000.. 15 =1111; where there is a1in the binary expression include the corresponding item from the sequence. To implement this you’ll need bitshift and binary operations:Also consider how you’d handle sequences longer than can be covered by an
int(hint: consider overflow and arithmetic carry).