LeetCode_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].
DFS + 剪枝
class Solution { public: void DFS(vector<int> &num, int size,vector<int> temp) { if(size == n){ result.push_back(temp); return ; } for(int i = 0; i< n; i++) { if(flag[i] || (i!= 0 &&flag[i-1] && num[i] == num[i-1] ) ) continue; temp[size] = num[i]; flag[i] = true; DFS(num, size+1, temp); flag[i] = false; } } vector<vector<int> > permuteUnique(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function n = num.size(); result.clear(); sort(num.begin(), num.end()); if(n == 0) return result; flag.resize(n,false); vector<int> temp(n,0) ; DFS(num,0,temp); return result ; } private : int n; vector<bool> flag; vector<vector<int>> result; };
这里解释下剪枝的原理: 有重复元素的时候,因为重复的元素处理无序所以导致重复,所以只要给重复的元素进入temp定义一个次序就可以去掉重复。这里定义次序的规则是: 先对所有元素排序对于有重复的元素,必须是排在后面的元素比排在前面的元素先进入temp
重写后,貌似比第一个版本要快一点
class Solution { public: void DFS(vector<int> &num, vector<int> &tp, vector<bool> flag) { if(num.size() == tp.size()){ res.push_back(tp); return; } for(int i = 0; i< num.size(); i++) { if(flag[i] == true) continue; if(i != 0 && num[i] == num[i-1] && flag[i-1] == false) continue; flag[i] = true; tp.push_back(num[i]); DFS(num, tp, flag); tp.pop_back(); flag[i] = false; } } vector<vector<int> > permuteUnique(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function res.clear(); int len = num.size(); if(len < 1) return res; sort(num.begin(), num.end()); vector<bool> flag(len, false); vector<int> tp; DFS(num, tp, flag); return res; } private: vector<vector<int>> res; };
--------------------------------------------------------------------天道酬勤!