[leetcode] 47. Permutations II

来源:互联网 发布:淘宝联盟如何购买省钱 编辑:程序博客网 时间:2024/06/08 03:12

Question:

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

For example,

[1,1,2] have the following unique permutations:[  [1,1,2],  [1,2,1],  [2,1,1]]

Solution:

简单递归,对每一个位置赋一个值即可。为了保证同一个位置不会赋值相同,事先用map记录数组而不是使用原数组,每次在一个位置使用map中的一个key,用value记录该key的个数即可。

class Solution {public:    vector<vector<int>> permuteUnique(vector<int>& nums) {        map<int, int> m;        for (int i : nums) {            if (m.find(i) != m.end())                m[i]++;            else                m[i] = 1;        }        vector<vector<int>> ret;        vector<int> tmp;        helper(m, ret, tmp, nums.size());        return ret;    }    void helper(map<int, int>& m, vector<vector<int>>& ret, vector<int>& tmp, const int& n) {        if (n == tmp.size()) {            ret.push_back(tmp);            return;        }        for (auto it = m.begin(); it != m.end(); it++) {            if (it->second > 0) {                it->second--;                tmp.push_back(it->first);                helper(m, ret, tmp, n);                tmp.pop_back();                it->second++;            }        }    }};
原创粉丝点击