Shirlies
宁静专注认真的程序媛~

题目:

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

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

链接:

http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:

递归n!

1、用数组标记当前字符为已访问

2、还需要用一个数组记录是否有重复的字符

代码:

 1 class Solution {
 2 
 3     void Permutation(vector<string> &ans, string result, string &str, bool *f, int depth, int end){
 4         if (depth == end){
 5             ans.push_back(result);
 6             return;
 7         }
 8 
 9         bool flag[60];
10         memset(flag, false, sizeof(flag));
11 
12         ++depth;
13         for (int index = 0; index < end; ++index){
14             if (!f[index]){
15                 if (str[index] >= 'a' && str[index] <= 'z' && !flag[str[index] - 'a']){
16                     flag[str[index] - 'a'] = true;
17                 }
18                 else if (str[index] >= 'A' && str[index] <= 'Z' && !flag[str[index] - 'A' + 26]){
19                     flag[str[index] - 'A' + 26] = true;
20                 }
21                 else{
22                     continue;
23                 }
24 
25                 f[index] = true;
26 
27                 result.push_back(str[index]);
28                 Permutation(ans, result, str, f, depth, end);
29                 result.pop_back();
30 
31                 f[index] = false;
32             }
33 
34 
35         }
36     }
37 public:
38     vector<string> Permutation(string str) {
39         vector<string> ans;
40 
41         if (str.empty()){
42             return ans;
43         }
44         string result;
45         bool f[10];
46         memset(f, false, sizeof(f));
47         Permutation(ans, result, str, f, 0, str.length());
48 
49         return ans;
50     }
51 };

 

posted on 2016-09-11 22:11  Shirlies  阅读(352)  评论(0)    收藏  举报