# leetcode 47 : Permutations II

323人阅读 评论(0)

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;
}
};

个人资料
等级：
访问量： 16万+
积分： 3277
排名： 1万+
最新评论