-
Notifications
You must be signed in to change notification settings - Fork 0
/
All unique permutation.txt
70 lines (46 loc) · 1.37 KB
/
All unique permutation.txt
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Given an array A of size N denoting collection of numbers that might contain duplicates, return all possible unique permutations.
NOTE: No 2 entries in the permutation sequence should be the same.
WARNING: DO NOT USE LIBRARY FUNCTION FOR GENERATING PERMUTATIONS. Example : next_permutations in C++ / itertools.permutations in python.
If you do, we will disqualify your submission retroactively and give you penalty points.
Problem Constraints
1 <= |A| <= 9
Input Format
Only argument is an integer array A of size N.
Output Format
Return a 2-D array denoting all possible unique permutation of the array.
Example Input
Input 1:
A = [1, 1, 2]
Input 2:
A = [1, 2]
Example Output
Output 1:
[ [1,1,2]
[1,2,1]
[2,1,1] ]
Output 2:
[ [1, 2]
[2, 1] ]
Example Explanation
Explanation 1:
All the possible unique permutation of array [1, 1, 2].
Explanation 2:
All the possible unique permutation of array [1, 2].
void solve(vector<vector<int> >&ans,vector<int> &A,int i){
if(i==A.size()){
ans.push_back(A);
return;
}
for(int j=i;j<A.size();j++){
swap(A[i],A[j]);
solve(ans,A,i+1);
swap(A[i],A[j]);
}
}
vector<vector<int> > Solution::permute(vector<int> &A) {
vector<vector<int>> ans;
solve(ans,A,0);
sort(ans.begin(),ans.end());
ans.resize(distance(ans.begin(),unique(ans.begin(),ans.end())));
return ans;
}