排列:给定一个字符,找出全排列,字符中可能存在重复的字符。
#include<iostream>
#include<string>
#include<set>
using namespace std;
void arrangement(string& input, int startIndex, set<string>& res)
{
if (startIndex == input.size())
{
res.insert(input);
return;
}
else
{
for (int i = startIndex; i < input.size(); i++)
{
char tmp = input[startIndex];
input[startIndex] = input[i];
input[i] = tmp; //交换两者之间的字符
arrangement(input, startIndex + 1, res); //递归调用
tmp = input[startIndex];
input[startIndex] = input[i];
input[i] = tmp; //字符还原
}
}
}
int main()
{
string input;
cin >> input;
set<string> res;
arrangement(input, 0, res);
cout << "result:" << endl;
for (auto item : res)
{
cout << item << endl;
}
return 0;
}
组合:给定一个字符,找出组合的结果,字符中可能存在重复的字符。
#include<iostream>
#include<algorithm>
#include<set>
#include<string>
using namespace std;
void combination(string input, int index, string& tmp, set<string>& res)
{
if (index == input.size())
{
res.insert(tmp);
return ;
}
else
{
string tmp1 = tmp;
combination(input, index + 1, tmp1, res);//当前字符不加入组合
tmp += input[index];
combination(input, index + 1, tmp, res);//当前字符加入组合
}
}
int main()
{
string input;
cin >> input;
sort(input.begin(), input.end());//将字符进行排序,目的统一字符出现的相对次序
set<string> res;//去重复
string tmp;
combination(input, 0, tmp, res);
cout << "result:" << endl;
for (auto item : res)
{
cout << item << endl;
}
return 0;
}