forked from mahendrarathore1742/leetcode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode0047-permutations-ii.cpp
More file actions
35 lines (32 loc) · 997 Bytes
/
leetcode0047-permutations-ii.cpp
File metadata and controls
35 lines (32 loc) · 997 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
* Copyright (C) 2018 all rights reserved.
*
* Author: Houmin Wei <houmin.wei@outlook.com>
*
* Source: https://leetcode.com/problems/permutations-ii
*
* Description:
* Given a collection of numbers that might contain duplicates, return all possible unique permutations.
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<vector<int>> ret;
dfs(nums, 0, ret);
return vector<vector<int>>(ret.begin(), ret.end());
}
void dfs(vector<int>& nums, int begin, set<vector<int>>& ret) {
if (begin == nums.size()) { ret.insert(nums); return; }
for (int i = begin; i < nums.size(); i++) {
if (i == begin || nums[i] != nums[begin]) {
swap(nums[begin], nums[i]);
dfs(nums, begin+1, ret);
swap(nums[begin], nums[i]);
}
}
}
};