1 題目描述
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。
輸入描述:
輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。
2 思路和方法
固定第一個字符,遞歸取得首位後面的各種字符串組合;再將第一個字符與後面每一個字符交換,同樣遞歸獲得其字符串組合;每次遞歸都是到最後一位時結束,遞歸的循環過程,就是從每個子串的第二個字符開始依次與第一個字符交換,然後繼續處理子串。
3 C++核心代碼
去重一:
class Solution {
public:
vector<string> result;
vector<string> Permutation(string str) {
if(str.length()==0)
return result;
permutation1(str,0);
sort(result.begin(), result.end());
return result;
}
void permutation1(string str, int begin){
if(begin==str.length())
{
result.push_back(str);
return;
}
for(int i = begin; str[i]!='\0'; i++) //每個元素與第一個元素交換
{
if(i!=begin && str[begin]==str[i]) //去重
continue;
swap(str[begin], str[i]);
permutation1(str, begin+1); //交換後,得到子序列,用函數perm得到子序列的全排列
swap(str[begin], str[i]); //最後,將元素交換回來,復原,然後交換另一個元素
}
}
};
去重2: https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
class Solution {
public:
vector<string> result;
vector<string> Permutation(string str) {
if(str.length()==0)
return result;
permutation1(str,0);
sort(result.begin(), result.end());
return result;
}
void permutation1(string str, int begin){
if(begin==str.length())
{
result.push_back(str);
return;
}
for(int i = begin; str[i]!='\0'; i++) //每個元素與第一個元素交換
{
if(i!=begin && str[begin]==str[i]) //去重
continue;
swap(str[begin], str[i]);
permutation1(str, begin+1); //交換後,得到子序列,用函數perm得到子序列的全排列
swap(str[begin], str[i]); //最後,將元素交換回來,復原,然後交換另一個元素
}
}
};
4 C++完整代碼
#include<stdio.h>
#include <iostream>
#include<stdlib.h>
#include<vector>
#include<string>
#include <algorithm>
using namespace std;
void swap(char &a, char &b) {
char temp = a;
a = b;
b = temp;
}
void permcore(string list, int low, int high, vector<string>& res) {
if (low == high &&
find(res.begin(), res.end(), list) == res.end()) { //去重
res.push_back(list);
}
else {
for (int i = low; i <= high; i++) {//每個元素與第一個元素交換
if (i == low || list[i] != list[low]) { //去重
swap(list[i], list[low]);
permcore(list, low + 1, high, res); //交換後,得到子序列,用函數perm得到子序列的全排列
swap(list[i], list[low]);//最後,將元素交換回來,復原,然後交換另一個元素
}
}
}
}
vector<string> perm(string str)
{
vector<string> res;
if (!str.empty())
permcore(str, 0, str.size() - 1, res);
return res;
}
int main()
{
vector<string> res;
string stdstr = "abb";
res = perm(stdstr);
for (auto s : res)
cout << s << endl;
cout << endl;
string stdstr2 = "aab";
res = perm(stdstr2);
for (auto s : res)
cout << s << endl;
cout << endl;
system("pause");
return 0;
}