描述
给出一个具有重复数字的列表,找出列表所有不同的排列。
您在真实的面试中是否遇到过这个题?
是
样例
给出列表 [1,2,2]
,不同的排列有:
[
[1,2,2],
[2,1,2],
[2,2,1]
]
挑战
使用递归和非递归分别完成该题。
递归方法:
参照16题,为排除重复元素,要保证需要进行交换的两数之间没有重复的数。
class Solution {
public:
/*
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int>> m_vectors;
vector<vector<int>> permuteUnique(vector<int> &nums) {
// write your code here
if(nums.size()>0){
perm(nums,0,nums.size()-1);
}else{
vector<int> n_vector;
m_vectors.push_back(n_vector);
}
return m_vectors;
}
void perm(vector<int> &nums,int p,int q){
if(p==q){
m_vectors.push_back(nums);
}else{
for(int i=p;i<=q;i++){
if(isswap(nums,p,i)){
swap(nums[p],nums[i]);
perm(nums,p+1,q);
swap(nums[p],nums[i]);
}
}
}
}
bool isswap(vector<int> &nums,int start,int end){
for(int i=start;i<end;i++){
if(nums[i]==nums[end]){
return false;
}
}
return true;
}
void swap(int &a,int &b){
if (a != b)
{
a ^= b;
b ^= a;
a ^= b;
}
}
};