美文网首页
47.Permutations II/全排列 II

47.Permutations II/全排列 II

作者: 蜜糖_7474 | 来源:发表于2019-05-20 13:38 被阅读0次

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

AC代码

void digui(vector<int>& nums, vector<int>& t, map<int, int>& mp,
           vector<vector<int>>& ans) {
    if (t.size() == nums.size()) {
        ans.push_back(t);
        return;
    }
    for (int i = 0; i < nums.size(); ++i) {
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        if (mp[nums[i]] > 0) {
            mp[nums[i]]--;
            t.push_back(nums[i]);
            digui(nums, t, mp, ans);
            t.pop_back();
            mp[nums[i]]++;
        }
    }
}

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> ans;
        vector<int> t;
        map<int, int> mp;
        for (int i = 0; i < nums.size(); ++i) mp[nums[i]]++;
        sort(nums.begin(), nums.end());
        digui(nums, t, mp, ans);
        return ans;
    }
};

总结

有点找到深度优先搜索的感觉了

相关文章

网友评论

      本文标题:47.Permutations II/全排列 II

      本文链接:https://www.haomeiwen.com/subject/mcqkzqtx.html