首页 > 其他 > 详细

剑指offer27:按字典序打印出该字符串中字符的所有排列

时间:2019-08-26 19:11:21      阅读:99      评论:0      收藏:0      [点我收藏+]

1 题目描述

  输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入描述:

  输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

2 思路和方法

  固定第一个字符,递归取得首位后面的各种字符串组合;再将第一个字符与后面每一个字符交换,同样递归获得其字符串组合;每次递归都是到最后一位时结束,递归的循环过程,就是从每个子串的第二个字符开始依次与第一个字符交换,然后继续处理子串。

3 C++核心代码

技术分享图片
 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 };
View Code

4 C++完整代码

技术分享图片
 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 }
View Code

参考资料

https://blog.csdn.net/JarvisKao/article/details/76999473

剑指offer27:按字典序打印出该字符串中字符的所有排列

原文:https://www.cnblogs.com/wxwhnu/p/11414103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!