剑指 Offer 38. 字符串的排列

2020-07-10

1.题目描述

输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

2.题解

1.递归+回溯
2.交换元素

3.代码

class Solution {
    
    
public:
    vector<string> permutation(string s) {
    
    
        int l=s.size();
        if (!l) return vector<string>(0);
        string str="";
        vector<bool> f(l,false);
        sort(s.begin(),s.end());
        dfs(str,s,0,l,f);
        return res;
    }

    void dfs(string str,string s,int step,int max_len,vector<bool> f){
    
    
        if (step==max_len){
    
    
            res.push_back(str);
            return;
        }
        char pre=' ';
        for (int i=0;i<max_len;i++){
    
    
            if (!f[i]&&s[i]!=pre){
    
    
                f[i]=true;
                dfs(str+s[i],s,step+1,max_len,f);
                pre=s[i];
                f[i]=false;
            }
        }
    }
    vector<string> res;
};
class Solution {
    
    
public:
    vector<string> permutation(string s) {
    
    
        int l=s.size();
        if (!l) return vector<string>(0);
        dfs(s,0,l);
        return res;
    }

    void dfs(string str,int step,int max_len){
    
    
        if (step==max_len){
    
    
            res.push_back(str);
            return;
        }
        for (int i=step;i<max_len;i++){
    
    
            bool f=true;
            for (int j=i+1;j<max_len;j++){
    
    
                if (str[j]==str[i]) {
    
    
                    f=false;
                    break;
                }
            }
            if (i==step||(str[i]!=str[step]&&f)){
    
    
                swap(str[i],str[step]);
                dfs(str,step+1,max_len);
                swap(str[i],str[step]);
            }
        }
    }
    vector<string> res;
};

猜你喜欢

转载自blog.csdn.net/qq_34600424/article/details/107270778