标签:
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> > permuteUnique(vector<int> &num) { vector<vector<int>> ans; if(num.empty()) return ans; permute(ans, num, 0); return ans; }
//不知道为什么 注释掉的这种 在我自己的电脑上就ok 但是提交就总是
Output Limit Exceeded?? //void permute(vector<vector<int>> &ans, vector<int> num, int k) //{ // if(k >= num.size()) // { // ans.push_back(num); // return; // } // for(int j = k; j < num.size(); j++) //和自己或后面交换 // { // if (j > k && num[j] == num[j-1]) continue; //prevent duplicates // swap(num[k], num[j]); // permute(ans, num, k + 1); // swap(num[k], num[j]); // } //} void permute(vector<vector<int>> &ans, vector<int> num, int k) { if(k >= num.size()) { ans.push_back(num); return; } vector<int> hash; for(int j = k; j < num.size(); j++) //和自己或后面交换 { if(find(hash.begin(), hash.end(), num[j]) == hash.end()) { hash.push_back(num[j]); swap(num[k], num[j]); permute(ans, num, k + 1); swap(num[k], num[j]); } } } };
【leetcode】Permutations II (middle)
标签:
原文地址:http://www.cnblogs.com/dplearning/p/4240089.html