我在这个递归排列代码中找不到一个简单的语句来跳过重复项。我已经到处查找,似乎只能找到使用swap或java的示例。根据我的理解,我认为我需要在for循环后面加一行代码。
谢谢!
#include "genlib.h"
#include "simpio.h"
#include <string>
#include <iostream>
void ListPermutations(string prefix, string rest);
int main() {
cout << "Enter some letters to list permutations: ";
string str = GetLine();
cout << endl << "The permutations are: " << endl;
ListPermutations("", str);
return 0;
}
void ListPermutations(string prefix, string rest)
{
if (rest == "")
{
cout << prefix << endl;
}
else
{
for (int i = 0; i < rest.length(); i++)
{
if (prefix != "" && !prefix[i]) continue; // <--- I tried adding this, but it doesn't work
cout << endl<< "prefix: " << prefix << " | rest: " << rest << endl;
string newPrefix = prefix + rest[i];
string newRest = rest.substr(0, i) + rest.substr(i+1);
ListPermutations(newPrefix, newRest);
}
}
}