Created
February 17, 2013 15:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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