-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAll Unique Permutations of an array.java
35 lines (35 loc) · 1.17 KB
/
All Unique Permutations of an array.java
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
static void help(ArrayList<Integer> arr,int n,HashSet<ArrayList<Integer>> mm,int index){
if(index==n){
ArrayList<Integer> nn = new ArrayList<>(arr);
mm.add(nn);
return;
}
for(int i=index;i<n;i++){
int a = arr.get(i);
int b = arr.get(index);
arr.set(i,b);
arr.set(index,a);
help(arr,n,mm,index+1);
arr.set(i,a);
arr.set(index,b);
}
}
static ArrayList<ArrayList<Integer>> uniquePerms(ArrayList<Integer> arr , int n) {
// code here
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
HashSet<ArrayList<Integer>> mm = new HashSet<>();
help(arr,n,mm,0);
for(ArrayList<Integer> temp:mm)ans.add(temp);
Collections.sort(ans, new Comparator<List<Integer>>() {
public int compare(List<Integer> a, List<Integer> b) {
int i = 0;
while(i<n) {
if(a.get(i).compareTo(b.get(i)) != 0)
return a.get(i).compareTo(b.get(i));
i++;
}
return 0;
}
});
return ans;
}