试试这个。我通常避免递归,但在这里效果很好:
#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
using std::vector;
using std::cout;
using std::endl;
using std::find;
void printVec(vector<char> &vec)
{
for(int i = 0; i < vec.size(); i++)
{
cout << vec[i];
}
cout << endl;
}
void incrementCharAvoidingDuplicates(vector<char> v, char &c)
{
// increment newChar until we find one not in the vector already
while(std::find(v.begin(), v.end(), c)!=v.end())
{
c++;
}
}
bool incrementVec(vector<char> &v)
{
if(v.size() == 0 || v.size() >= 25)
return false;
//try incrementing the final character
char newChar = v.back() + 1;
incrementCharAvoidingDuplicates(v, newChar);
// if it's still in range, we have succesfully incremented the vector
if(newChar <= 'z')
{
v.back() = newChar;
return true;
}
// if not (e.g. "abz") then remove the final character and try to increment the base part instead
else
{
vector<char> w(v.begin(), v.end() - 1);
if(incrementVec(w))
{
// we succeeded in incrementing the base ... so find a remaining character that doesn't conflict and append it
// (note there will always be one since we insisted size < 25)
v.resize(w.size());
std::copy(w.begin(), w.end(), v.begin());
char newChar = 'a';
incrementCharAvoidingDuplicates(v, newChar);
v.push_back(newChar);
return true;
}
// otherwise we could not increment the final char, could not increment the base...so we are done
else
{
return false;
}
}
}
int main()
{
static const char arr[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','v','w','x','y','z'};
vector<char> originalAlphabet (arr, arr + sizeof(arr) / sizeof(arr[0]) );
vector<char> currentWord;
int desiredWordLength;
for(desiredWordLength = 1; desiredWordLength < 25; desiredWordLength++)
{
currentWord.clear();
//build first list e.g. a, abc, abcdef, ...
for(int j = 0; j < desiredWordLength; j++)
{
currentWord.push_back(originalAlphabet[j]);
}
do{
printVec(currentWord);
} while( incrementVec(currentWord));
}
return 0;
}