具有任意数量级别的简单算法(也做了很多复制字符串):
class StringCombinations {
public:
// filled somehow
std::vector<std::pair<char, char> > choices;
void printStrings(size_t level, std::string prefix) {
assert(level < choices.size());
if (level == choices.size() - 1) {
cout << prefix << choices[i].first();
cout << prefix << choices[i].second();
} else {
printStrings(level +1, prefix + choices[i].first());
printStrings(level +1, prefix + choices[i].second());
}
}
}
像这样调用:
StringCombinations sc;
// Set the choices table somehow.
...
sc.printStrings(0, "");
当然,选择表也可以是另一个作为常量引用传递的方法参数,如果您为此使用静态方法更方便的话。
--
一个更好的替代方案(只是对 3 个级别提出的 otehr 答案的 n 级别的概括),而不需要对递归调用进行所有复制(尽管不太容易理解):
cout <<
请注意,mystring +=
如果您不直接打印,当然可以替换。
// all strings have size 2, 0'th char and 1'st char correspond to the choices
std::vector<std::string> choices;
void printStrings() {
for (size_t i = 0; i < static_cast<size_t>(pow(2, choices.size())); ++i) {
for (size_t j = 0; j < choices.size(); ++j) {
// Checks the bit in i (from the right) that fits the current level (j).
cout << choices[j][i & (j << x)];
// 2^#levels different values of i, ensure as many different outcomes
// (disregarding trivial choices between, e.g., 'a' and 'a'
}
}
}