剑指 Offer 38. 字符串的排列

剑指 Offer 38. 字符串的排列

题目

输入一个字符串,打印出该字符串中字符的所有排列。

你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

思路

因为有重复字符,所以不能通过记录哪个使用了哪个没使用来 dfs。而是统计所有不重复的字符,并记录每个字符的个数,然后进行 dfs。

方法二:采用下一个排列的方法去做

代码

class Solution {
private:
    vector<string> ans;
    int cnt[200];
    vector<char> chars;
public:
    void dfs(int now, int n, string& str) {
        if (now > n) {
            ans.push_back(str);
            return;
        }
        for (const auto& ch : chars) {
            if (cnt[ch]) {
                str += ch;
                --cnt[ch];
                dfs(now + 1, n, str);
                str.pop_back();
                ++cnt[ch];
            }
        }
    }
    vector<string> permutation(string s) {
        memset(cnt, 0, sizeof(cnt));
        for (const auto& ch : s) {
            if (!cnt[ch]) chars.push_back(ch);
            ++cnt[ch];
        }
        string str;
        dfs(1, s.size(), str);
        return ans;
    }
};
posted @ 2022-04-14 16:31  沐灵_hh  阅读(7)  评论(0编辑  收藏  举报