剑指offer 字符串的排列

题目描述

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

输入描述:

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

 

分析:回溯法。

 1 class Solution {
 2 private:
 3     void dfs(vector<string> &res, string &s, vector<bool> &visited, const string str, int depth, int len) {
 4         if (depth == len - 1) {
 5             if (find(res.begin(), res.end(), s) == res.end()) { //find函数在头文件algorithm中
 6                 res.push_back(s);
 7             }
 8             return ;
 9         }
10         for (int i = 0; i < len; i++) {
11             if ( !visited[i]) {
12                 visited[i] = true;
13                 s += str[i];
14                 dfs(res, s, visited, str, depth + 1, len);
15                 s.pop_back();
16                 visited[i] = false;
17             }
18         }
19     }
20 public:
21     vector<string> Permutation(string str) {
22         sort(str.begin(), str.end());
23         vector<string> res;
24         string s;
25         int len = str.length();
26         vector<bool> visited(len, false);
27         for (int i = 0; i < len; i++) {
28             visited[i] = true;
29             s += str[i];
30             dfs(res, s, visited, str, 0, len);
31             s.pop_back();
32             visited[i] = false;
33         }
34         return res;
35     }
36 };

 

posted @ 2019-08-20 10:33  琴影  阅读(207)  评论(0编辑  收藏  举报