LeetCode 【回溯】面试题 08.08. 有重复字符串的排列组合

有重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合。

示例1:

 输入:S = "qqe"
 输出:["eqq","qeq","qqe"]
示例2:

 输入:S = "ab"
 输出:["ab", "ba"]
提示:

字符都是英文字母。
字符串长度在[1, 9]之间。

题解:

肯定是用回溯的,一开始想到在每次循环中,都进行遍历,找到当前位置对应的。

/abc/

     a
    / \
   b   c
  /     \
 c       b

/abbc/

          a
         / \
        b   c(略)
       / \
      b   c
     /     \
    c       b

 这样做的好处就是写起来简单,但是如果遇到 /aaaaaa/这样的,如果还是简单的遍历,很有可能会循环2^6,然而实际上只需要一次。

所以可以做一个字典,每当采用了一个字符之后,就把字典中对应的字符的second减一。

class Solution {
public:
    vector<string> permutation(string S) {
        vector<string> vec;
        if (S=="") {
            vec.push_back("");
            return vec;
        } 
        map<char,int> dict;
        build_map(S,dict);
        string temp = "";
        sub_process(temp,S.size(),vec,dict);
        return vec;
    }
    void sub_process (string sub_s, int length, vector<string>& ans, map<char,int>& dict){
        //ans.push_back(sub_s);
        if(sub_s.size()==length) {
            ans.push_back(sub_s);
            return;
        }
        auto iter = dict.begin();
        for(iter;iter!=dict.end();iter++){
            if (iter->second == 0) continue;
            iter->second--;
            string new_sub_s = sub_s;
            new_sub_s.push_back(iter->first);
            sub_process(new_sub_s,length,ans,dict);
            iter->second++;
        }
        
    }
    void build_map(string S,map<char,int> &dict){
        sort(S.begin(),S.end());
        int count = 1;
        for(int i=0;i<S.size();i++){
            if(S[i]!=S[i+1]){
                dict[S[i]]=count;
                count=1;
            }else{
                count++;
            }
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值