【剑指offer】【回溯】38. 字符串的排列

回溯

class Solution {
public:
    vector<string> res;
    vector<string> permutation(string s) {
        int cur = 0;
        permutation(s, cur);
        return res;
    }
    void permutation(string &s, int cur){
        if(cur == s.size() - 1)
            res.push_back(s);
        else
            for(int i = cur; i < s.size(); i++){
                if(judge(s, cur, i)) continue; //从cur开始,遍历没有遍历过的字符
                swap(s[cur], s[i]);
                permutation(s, cur + 1);
                swap(s[cur], s[i]);
            }
    }
    bool judge(string& s, int start, int end)
    {
        for(int i = start; i < end; ++i)
            if(s[i] == s[end]) return true;
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/Trevo/p/12803820.html