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]
.
参考:http://blog.csdn.net/morewindows/article/details/7370155
//交换前去掉判断要交换前是否出现过要交换的字符,如出现则继续下一个字符,忽略当前的!
//去重排序题
vector<vector<int> > permuteUnique(vector<int> &num) {
vector< vector<int> > num_vector ;
permute(num , 0,num_vector);
return num_vector;
}
void permute(vector<int> &num , int index,vector< vector<int> >&num_vector )
{
if(index >= num.size())
{
num_vector.push_back(num);
}
else
for(int i = index;i < num.size();i++)
{
if(check_is_swap(num,index,i))
{
swap(num[i],num[index]);
permute(num ,index+1,num_vector);
swap(num[i],num[index]);
}
}
}
//形如ABB
//如 第一个元素与第二个交换为:BAB 再第二个与第三个交换:BBA
//第一个与第三个交换 :BBA 再第二个与第三个交换:BAB
//可知以上重复,重复的原因是:即要交换的B前出现了B,导致交换有重复的可能!
bool check_is_swap(vector<int> &num,int start,int end)
{
for(int i = start;i < end;i++)
{
if(num[i] == num[end])
return false;
}
return true;
}