首页 > 其他 > 详细

字符串的排列

时间:2017-12-26 13:36:11      阅读:263      评论:0      收藏:0      [点我收藏+]

题目描述

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

输入描述:

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

思路:回溯法,排列树。由于字符有重复,所以要去重;由于要按字典序打印,所以最后要排序
 1 class Solution {
 2 public:
 3     void backtrace(string &str, vector<string> &res, int n)
 4     {
 5         if(n==str.size())
 6         {
 7             res.push_back(str);
 8             return;
 9         }else{
10             for(int i=n; i<str.size(); ++i)
11             {
12                 if(i!=n && str[i]==str[n])continue;//去重
13                 char tmp=str[n];//交换
14                 str[n]=str[i];
15                 str[i]=tmp;
16                 backtrace(str, res, n+1);//递归
17                 tmp=str[n];//换回来
18                 str[n]=str[i];
19                 str[i]=tmp;
20             }
21         }
22     }
23     vector<string> Permutation(string str) {
24         vector<string> res;
25         if(str.size()==0)return res;
26         backtrace(str, res, 0);
27         std::sort(res.begin(), res.end());//排序
28         return res;
29     }
30 };

 

字符串的排列

原文:https://www.cnblogs.com/jeysin/p/8117205.html

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