-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniqueSubset.java
More file actions
73 lines (63 loc) · 1.92 KB
/
UniqueSubset.java
File metadata and controls
73 lines (63 loc) · 1.92 KB
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
71
72
73
//Problem Link :: https://practice.geeksforgeeks.org/problems/subsets-1587115621/1
//{ Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
for(int t=0;t<testCases;t++){
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
ArrayList <ArrayList<Integer>> res = new solve().AllSubsets(arr,n);
for (int i = 0; i < res.size (); i++)
{
System.out.print ("(");
for (int j = 0; j < res.get(i).size (); j++)
{
if (j != res.get(i).size()-1)
System.out.print ((res.get(i)).get(j) + " ");
else
System.out.print ((res.get(i)).get(j));
}
System.out.print (")");
}
System.out.println();
}
}
}
// } Driver Code Ends
class solve
{
//Function to find all possible unique subsets.
public static ArrayList <ArrayList <Integer>> AllSubsets(int arr[], int n)
{
// your code here
Arrays.sort(arr);
LinkedHashSet<ArrayList<Integer>> res = new LinkedHashSet<>();
ArrayList<Integer> op = new ArrayList<>();
//call
res.add(op);
uniqueSubset(arr,0,res,op);
//System.out.println(subset);
return new ArrayList<>(res);
}
public static void uniqueSubset(int arr[],int indx,LinkedHashSet<ArrayList<Integer>> res,ArrayList<Integer> op){
//Base Case ::
if(indx==arr.length){
return;
}
//pick
op.add(arr[indx]);
res.add(new ArrayList<Integer>(op));
uniqueSubset(arr,indx+1,res,op);
//not pick case :: just remove last ele from op::
op.remove(op.size()-1);
uniqueSubset(arr,indx+1,res,op);
}
}