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]
.
首先分析一下與Permutations有何差異。
記當前位置為start,當前排列數組為cur
1、cur[start]與cur[start]值相同的元素交換位置會產生大量重復。
如:1,3,2,1
兩個1互換位置之后,后續的所有排列都是重復的。
2、cur[start]與其他相同值的元素多次交換位置會產生大量重復。
如:1,2,3,2
1與兩個2互換位置后,后續的所有排列都是重復的。
因此改變在於:
對於同一個值,只交換一次,否則跳過。
為了保證這一點,必須對cur數組start位置之后的元素排序,這樣可以跳過重復元素。
若不排序會產生如下問題:
0,0,1,9 --> 9,0,1,0
0就不連續了,無法進行判斷去重,結果又會產生重復。
class Solution { public: vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > ret; Helper(ret, num, 0); return ret; } void Helper(vector<vector<int> >& ret, vector<int> num, int pos) { if(pos == num.size()-1) ret.push_back(num); else { sort(num.begin()+pos, num.end()); for(int i = pos; i < num.size(); i ++) { if(i != pos && num[i] == num[i-1]) continue; swap(num[pos], num[i]); Helper(ret, num, pos+1); swap(num[pos], num[i]); } } } };