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]
.
Backtracking
class Solution { private: vector<vector<int> > ret; public: void perm(vector<int> &num,int i,int len){ if(i==len){ ret.push_back(num); return; } for(int j=i;j<len;++j){ if(!isSwap(num,i,j)) continue; swap(num[i],num[j]); perm(num,i+1,len); swap(num[j],num[i]); } } bool isSwap(vector<int>& num, int i, int j) { while (num[i] != num[j] && i < j) i++; if (i == j) return true; else return false; } vector<vector<int> > permuteUnique(vector<int> &num) { int len=num.size(); ret.clear(); sort(num.begin(), num.end()); perm(num,0,len); return ret; } };
参考http://blog.csdn.net/morewindows/article/details/7370155