当前位置:网站首页>Sword finger offer 38 Arrangement of strings [no description written]

Sword finger offer 38 Arrangement of strings [no description written]

2022-07-07 10:22:00 qq_ forty-two million one hundred and twenty thousand eight hun

subject

Enter a string , Print out all the permutations of the characters in the string .
You can return this array of strings in any order , But there's no repetition in it .

Example

Input :s = “abc”
Output :[“abc”,“acb”,“bac”,“bca”,“cab”,“cba”]

C++ Realization

class Solution {
    
public:
    vector<string> permutation(string s) {
    
       dfs(s,0);
       return ans;   
    }
private:
    vector<string> ans;
    void dfs(string s,int pos)
    {
    
        bool flag = true;
        if(pos == s.size()-1)
        {
    
            ans.push_back(s);
            return ;
        }
        set<int> st;// Used to store letters that have been used in the current position , Used for de pruning 
        for(int i = pos;i < s.size();++i)
        {
    
            if(st.find(s[i]) != st.end()) continue; // If the current letter has been used, skip , namely dfs Middle pruning operation 
            st.insert(s[i]);
            swap(s[i],s[pos]);
            dfs(s,pos+1);
            swap(s[i],s[pos]);
        }
    } 
};
原网站

版权声明
本文为[qq_ forty-two million one hundred and twenty thousand eight hun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130623100593.html