题解 | #字符串的排列#

字符串的排列

http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7

回溯(深度优先搜索)。回溯求排列使用了一个标记数组used。最终的结果用set去重。

class Solution {
public:
    void dfs(string& str,vector<string>& result,string& path,vector<bool>& used){
        if(path.size()==str.size()){
            result.push_back(path);
            return;
        }
        for(int i=0;i<str.size();i++){
            if(used[i]) continue;
            used[i]=true;
            path.push_back(str[i]);
            dfs(str,result,path,used);
            path.pop_back();
            used[i]=false;
        }
    }
    
    vector<string> Permutation(string str) {
        vector<string> result{};
        string path{};
        vector<bool> used(str.size(),false);
        dfs(str, result, path, used);
        set<string> str_set{result.begin(),result.end()};
        vector<string> res{str_set.begin(),str_set.end()};
        return res;
    }
};


全部评论

相关推荐

把实习生当正职使昨天第一天就加班,晚上连口饭都没吃上,以后日子咋过,我不想干了
码农索隆:实习不怕忙,就怕干的活重复且没难度,要干就干那种有深度有难度的任务,这样才能快速的提升
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-23 16:31
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务