【leetcode】Permutations II (middle)

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], and [2,1,1].

 
思路:
找规律递归 一个数跟自己后面的数字交换如 1 2 2 第一个数字和第2个数字换, 但是不换重复的数字 第一个数字和第三个数字就不换了
class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        vector<vector<int>> ans;
        if(num.empty())
            return ans;

        permute(ans,  num, 0);
        return ans;
    }
   //不知道为什么 注释掉的这种 在我自己的电脑上就ok 但是提交就总是Output Limit Exceeded??
//void permute(vector<vector<int>> &ans, vector<int> num, int k) //{ // if(k >= num.size()) // { // ans.push_back(num); // return; // } // for(int j = k; j < num.size(); j++) //和自己或后面交换 // { // if (j > k && num[j] == num[j-1]) continue; //prevent duplicates // swap(num[k], num[j]); // permute(ans, num, k + 1); // swap(num[k], num[j]); // } //} void permute(vector<vector<int>> &ans, vector<int> num, int k) { if(k >= num.size()) { ans.push_back(num); return; } vector<int> hash; for(int j = k; j < num.size(); j++) //和自己或后面交换 { if(find(hash.begin(), hash.end(), num[j]) == hash.end()) { hash.push_back(num[j]); swap(num[k], num[j]); permute(ans, num, k + 1); swap(num[k], num[j]); } } } };
原文地址:https://www.cnblogs.com/dplearning/p/4240089.html