面试题 08.08. 有重复字符串的排列组合

题目:

 

 

解答:

在无重复字符代码的基础上先对字符串进行排序,这样重复字符必然相邻,然后在回溯过程中加一句判断条件去除重复排列。

 1 class Solution
 2 {
 3 public:
 4     vector<string> permutation(string S)
 5     {
 6         vector<string> res;
 7         sort(S.begin(), S.end());   //先排列,使得重复字符相邻,便于后面去重
 8         backTrack(res, S, 0);
 9         return res;
10     }
11 
12     void backTrack(vector<string> &res, string S, int begin)
13     {
14         if (begin == S.size())
15         {
16             res.push_back(S);
17         }
18         for (int i = begin; i < S.size(); ++i)
19         {
20             /*因为首次交换是i == begin,S[i]与自身交换
21             因此考虑两种重复情况的去除
22             1.S[i] == S[i-1]
23             2.S[i] == S[begin]*/
24             if (i > begin && (S[i] == S[i - 1] || S[i] == S[begin]))
25             {
26                 continue;
27             }
28             else
29             {
30                 swap(S[begin], S[i]);
31                 backTrack(res, S, begin + 1);    //DFS
32                 swap(S[begin], S[i]);
33             }
34         }
35     }
36 };

 

posted @ 2020-05-09 23:37  梦醒潇湘  阅读(481)  评论(0)    收藏  举报