固定第一个字符,递归取得首位后面的各种字符串组合;再将第一个字符与后面每一个字符交换,同样递归获得其字符串组合;每次递归都是到最后一位时结束,递归的循环过程,就是从每个子串的第二个字符开始依次与第一个字符交换,然后继续处理子串。
1 class Solution { 2 public: 3 vector<string> result; 4 vector<string> Permutation(string str) { 5 if(str.length()==0) 6 return result; 7 permutation1(str,0); 8 sort(result.begin(),result.end()); 9 return result; 10 } 11 void permutation1(string str,int begin){ 12 if(begin==str.length()) 13 { 14 result.push_back(str); 15 return; 16 } 17 for(int i = begin;str[i]!=‘\0‘;i++) 18 { 19 if(i!=begin&&str[begin]==str[i]) 20 continue; 21 swap(str[begin],str[i]); 22 permutation1(str,begin+1); 23 swap(str[begin],str[i]); 24 } 25 } 26 };
1 #include <stdio.h> 2 #include <vector> 3 #include <iostream> 4 #include <string> 5 6 using namespace std; 7 8 void swap(char &a, char &b) { 9 char temp = a; 10 a = b; 11 b = temp; 12 } 13 void permcore(string list, int low, int high, vector<string>& res) { 14 if (low == high && 15 find(res.begin(), res.end(), list) == res.end()) { //去重 16 res.push_back(list); 17 } 18 else { 19 for (int i = low; i <= high; i++) {//每个元素与第一个元素交换 20 if (i == low || list[i] != list[low]) { //去重 21 swap(list[i], list[low]); 22 permcore(list, low + 1, high, res); //交换后,得到子序列,用函数perm得到子序列的全排列 23 swap(list[i], list[low]);//最后,将元素交换回来,复原,然后交换另一个元素 24 } 25 } 26 } 27 } 28 29 vector<string> perm(string str) 30 { 31 vector<string> res; 32 if (!str.empty()) 33 permcore(str, 0, str.size() - 1, res); 34 return res; 35 } 36 37 int main() 38 { 39 vector<string> res; 40 string stdstr = "abb"; 41 res = perm(stdstr); 42 for (auto s : res) 43 cout << s << endl; 44 cout << endl; 45 46 string stdstr2 = "aab"; 47 res = perm(stdstr2); 48 for (auto s : res) 49 cout << s << endl; 50 cout << endl; 51 52 system("pause"); 53 return 0; 54 }
https://blog.csdn.net/JarvisKao/article/details/76999473
原文:https://www.cnblogs.com/wxwhnu/p/11414103.html