Permutations II

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].

思路:全排列问题;按照递归的思想,从“第一个字符”开始,依次与后面各字符交换。

          对于重复数字出现的数字,进行排序,在递归时不用交换,否则超时!

          用set集合可以去重;

    

class Solution {
public:
    vector<int> temp;
    set< vector<int> > ans;
    vector< vector<int> > ans_end;
    void permute1(vector<int>& nums,int index)
    {
        int i = 0;
        int j = 0;
        int temp;
        if(index == nums.size())
         {
             ans.insert(nums);
             return ;
         }
        for(i = index;i<nums.size();i++)
        {
            if(nums[index] == nums[i] && i>index)
                continue;
            else
            {
                 temp = nums[i];
                 nums[i] = nums[index];
                 nums[index] = temp;

            }
              permute1(nums,index+1);
              if(nums[index] != nums[i] && i>index)
                {
                    temp = nums[index];
                    nums[index] = nums[i];
                    nums[i] = temp;
                }

        }
    }
    vector<vector<int> > permuteUnique(vector<int>& nums){
        int n = nums.size();
        if(n == 0)
          return ans_end;
        sort(nums.begin(),nums.end());
        permute1(nums,0);
        set<vector<int> > ::iterator it;
        it = ans.begin();
        while(it!=ans.end())
        {
            ans_end.push_back(*it);
            it++;
        }
        return ans_end;
    }
};

点赞