# leetcode 47 : 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].

//递归，去重-交换时同值元素之交换一次，做一次排头
class Solution {
vector > ret;
int N;

public:
void perm(vector &nums, int i){
if( i == N){
ret.push_back(nums);
}
set setNums;
for(int j = i; j < N; j++){
//没有交换过的元素才交换
if( setNums.find(nums[j])==setNums.end() )
{
setNums.insert(nums[j]);
swap(nums[i], nums[j]);
perm(nums, i + 1);
swap(nums[j], nums[i]);
}
}
}

vector> permuteUnique(vector& nums) {
N = nums.size();
ret.clear();
perm(nums, 0);
return ret;
}
};
//next_permute
class Solution {
public:
//不循环
bool next_permute(vector& nums){
if(nums.size()==0||nums.size()==1)
return false;
vector::iterator itF=nums.end()-2;
vector::iterator itS=nums.end()-1;
while(true)
{
if(*itF<*itS)
{
vector::iterator tmpIt = nums.end()-1;
while(*tmpIt<=*itF)
tmpIt--;
int tmp=*itF;
*itF=*tmpIt;
*tmpIt=tmp;
break;
}
if(itF==nums.begin())
{
return false;
}
itF--;
itS--;
}
reverse(itS,nums.end());
return true;
}
vector> permuteUnique(vector& nums) {
vector> ret;
sort(nums.begin(),nums.end());
ret.push_back(nums);
while(next_permute(nums))
ret.push_back(nums);
return ret;
}
};

#### 【leetcode】【47】Permutations II

2016-03-01 10:17:28

#### Leetcode 47. Permutations II

2016-03-28 21:46:07

#### [leetcode 47] Permutations II

2015-01-11 11:22:03

#### LeetCode #47 - Permutations II

2018-03-31 10:51:46

#### leetcode——47——Permutations II

2016-04-16 20:01:09

#### LeetCode 47 - Permutations II

2016-03-04 18:32:17

#### leetcode 47:Permutations II

2015-11-07 16:20:03

#### Leetcode 47 Permutations II

2017-03-25 08:20:27

#### leetcode || 47、 Permutations II

2015-03-30 16:17:55

#### leetcode 47: Permutations II

2015-07-26 13:41:55