【发布时间】:2011-12-23 05:16:17
【问题描述】:
我很难找到一个简单的语句来跳过此递归排列代码的重复项。我到处寻找,似乎只找到使用交换或 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);
}
}
}
【问题讨论】:
-
我有强烈的感觉,你可以生成它们,这样一开始就不会发出重复的内容。但是,我的大脑现在处于故障状态,我现在似乎无法想象它
-
@sehe - 请参阅下面的答案 - 您只需要在开始之前在 str 上调用 sort ,并且只为每个唯一的 char 递归一次。排序可能甚至没有必要......但我现在不知道如果没有它它是否可以工作
标签: c++ string recursion permutation