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]
.
思路:
含有重复数字的全排列,关键是去重。首先排序,重复的元素相邻。如果当前元素与之前元素相等,如果之前元素还未被访问,则当前元素不可访问。换句话说,当前元素与前一个元素相等,只有当前一个元素被访问时,当前元素才能被访问。从而实现了去重。
题解:
class Solution { public: vector<vector<int> > res; vector<int> tmp; void dfs(vector<int> &num, bool visited[], int index) { if(index==num.size()) { res.push_back(tmp); return; } for(int i=0;i<num.size();i++) { if(!visited[i]) { if(i!=0 && num[i]==num[i-1] && !visited[i-1]) continue; tmp.push_back(num[i]); visited[i] = true; dfs(num, visited, index+1); visited[i] = false; tmp.pop_back(); } } } vector<vector<int> > permuteUnique(vector<int> &num) { int n = num.size(); bool *visited = new bool [n]; memset(visited, false, sizeof(bool)*n); sort(num.begin(), num.end()); dfs(num, visited, 0); return res; } };