I need to work out the correct algorithm for generating all the possible subsequences of a string.
Subsequence:
http://en.wikipedia.org/wiki/Subsequence
eg.
string:
ABACUS
subsequences:
1 >> A, B, A, C, U, S
2 >> AB, AA, AC, AU, AS, BA, BC, BU, BS, AC, AU, AS, CU, CS, US
3 >> ABA, ABC, ABU, ABS, AAC, AAU, AAS, ACU, ACS, AUS, BAC, BAU, BAS, BCU, BCS, BUS, ACU, ACS, AUS, CUS
4 >> ABAC, ABAU, ABAS, ABCU, ABCS, ABUS, AACU, AACS, ACUS, BACU, BACS, BCUS, ACUS
5 >> etc...
So far, I can work out what the
next subsequence is, for the position of each character at least:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
string next(string sub, int max) {
int length = sub.length();
int pos = length - 1;
//find first digit that can be increased
while(pos >= 0)
{
if(sub[pos] - '0' == max - (length - 1 - pos))
pos--;
else
break;
}
sub[pos]++; //increase digit
//update other digits
for(int a = pos+1; a < length; a++)
sub[a] = sub[a-1] + 1;
return sub;
}
|
The problem is, this cannot determine when the last subsequence for that length has been found, so my output will look something like this (where the string is 1234567 and the length is 6):
123456
123457
123467
123567
124567
134567
234567
������
������
������
|
So, how can I work out when the last subsequence is reached? And is there a specific algorithm for finding all the subsequenes?