|
| 1 | +//Problem Link :: https://practice.geeksforgeeks.org/problems/subsets-1587115621/1 |
| 2 | + |
| 3 | + |
| 4 | +//{ Driver Code Starts |
| 5 | +import java.util.*; |
| 6 | +import java.lang.*; |
| 7 | +import java.io.*; |
| 8 | + |
| 9 | +class GFG { |
| 10 | + |
| 11 | + |
| 12 | + public static void main (String[] args) { |
| 13 | + Scanner sc = new Scanner(System.in); |
| 14 | + int testCases = sc.nextInt(); |
| 15 | + for(int t=0;t<testCases;t++){ |
| 16 | + int n = sc.nextInt(); |
| 17 | + int arr[] = new int[n]; |
| 18 | + for(int i=0;i<n;i++){ |
| 19 | + arr[i] = sc.nextInt(); |
| 20 | + } |
| 21 | + Arrays.sort(arr); |
| 22 | + ArrayList <ArrayList<Integer>> res = new solve().AllSubsets(arr,n); |
| 23 | + for (int i = 0; i < res.size (); i++) |
| 24 | + { |
| 25 | + System.out.print ("("); |
| 26 | + for (int j = 0; j < res.get(i).size (); j++) |
| 27 | + { |
| 28 | + if (j != res.get(i).size()-1) |
| 29 | + System.out.print ((res.get(i)).get(j) + " "); |
| 30 | + else |
| 31 | + System.out.print ((res.get(i)).get(j)); |
| 32 | + } |
| 33 | + System.out.print (")"); |
| 34 | + |
| 35 | + } |
| 36 | + System.out.println(); |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | +// } Driver Code Ends |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +class solve |
| 46 | +{ |
| 47 | + //Function to find all possible unique subsets. |
| 48 | + public static ArrayList <ArrayList <Integer>> AllSubsets(int arr[], int n) |
| 49 | + { |
| 50 | + // your code here |
| 51 | + Arrays.sort(arr); |
| 52 | + LinkedHashSet<ArrayList<Integer>> res = new LinkedHashSet<>(); |
| 53 | + ArrayList<Integer> op = new ArrayList<>(); |
| 54 | + //call |
| 55 | + res.add(op); |
| 56 | + uniqueSubset(arr,0,res,op); |
| 57 | + //System.out.println(subset); |
| 58 | + return new ArrayList<>(res); |
| 59 | + } |
| 60 | + public static void uniqueSubset(int arr[],int indx,LinkedHashSet<ArrayList<Integer>> res,ArrayList<Integer> op){ |
| 61 | + //Base Case :: |
| 62 | + if(indx==arr.length){ |
| 63 | + return; |
| 64 | + } |
| 65 | + //pick |
| 66 | + op.add(arr[indx]); |
| 67 | + res.add(new ArrayList<Integer>(op)); |
| 68 | + uniqueSubset(arr,indx+1,res,op); |
| 69 | + //not pick case :: just remove last ele from op:: |
| 70 | + op.remove(op.size()-1); |
| 71 | + uniqueSubset(arr,indx+1,res,op); |
| 72 | + } |
| 73 | +} |
0 commit comments