Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 15:39
Show Gist options
  • Select an option

  • Save pdu/4971918 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971918 to your computer and use it in GitHub Desktop.
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]. http://leetcode.com/onlinejudge#question_47
#include <tr1::unordered_map>
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
int n = num.size();
vector<vector<int> > ans;
vector<int> id(n);
for (int i = 0; i < n; ++i)
id[i] = i;
ans.push_back(num);
map<vector<int>, bool> hash;
hash[num] = true;
while (next_permutation(id.begin(), id.end())) {
vector<int> tmp(n);
for (int i = 0; i < n; ++i)
tmp[i] = num[id[i]];
if (hash.find(tmp) == hash.end()) {
hash[tmp] = true;
ans.push_back(tmp);
}
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment