题解 | #字符串的排列#

字符串的排列

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

天然想法使用字典来对字符计数,可以想象把相同字符放在一个桶中,假设排列字符串长度为n,不同字符个数为m,那么有n个level,m个桶。开始默认0层字符串为空串。每一个level从m个桶中有字符一个桶中取,取完拼接上上一层的字符串。到第n层把结果push到数组中,输出。语文不好,表述不是特别清晰,希望谅解。

class Solution {
public:
    vector<string> res;
    int n = 0;
    vector<string> Permutation(string str) {
        map<char, int> m;
        for(char c : str){
            m[c]++;
        }
        n = str.size();
        MapPermutation(m,1,"");
        return res;
    }
    
    void MapPermutation(map<char, int> m,int level,string s) {
        for(auto& v : m){
            if(v.second > 0){
                v.second -= 1;
                if(level == n){
                    res.push_back(s+v.first);
                }else{
                    MapPermutation(m,level+1,s+v.first);
                }
                v.second += 1;
            }
        }
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
迷茫的大四🐶:摊牌了,我是25届的,你们也不招我
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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