Java Program to Print All Unique Subsets in an Array of Subsets Using Bit Manipulation
Last Updated :
21 Apr, 2021
Given an integer array of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets and should return the solution in any order.
Illustration:
Input: array = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Input: array = [0]
Output: [[],[0]]
Approach 1
Algorithm
- Generate all possible binary bitmasks of length n.
- Map a subset to each bitmask
- 1 on the ith position in the bitmask means the presence of nums[i] in the subset
- 0 means its absence.
- Return output list.
Implementation:
Example
Java
import java.io.*;
import java.util.*;
class GFG {
static List<List<Integer> > subsets( int [] nums)
{
List<List<Integer> > output = new ArrayList<>();
int n = nums.length;
for ( int i = ( int )Math.pow( 2 , n);
i < ( int )Math.pow( 2 , n + 1 ); ++i) {
String bitmask
= Integer.toBinaryString(i).substring( 1 );
List<Integer> curr = new ArrayList<>();
for ( int j = 0 ; j < n; ++j) {
if (bitmask.charAt(j) == '1' )
curr.add(nums[j]);
}
output.add(curr);
}
return output;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 };
List<List<Integer> > output = subsets(arr);
System.out.println(output);
}
}
|
Output
[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
Complexity Analysis:
- Time Complexity:- O(N x 2^N) to generate all subsets and then copy them into the output list.
- Space Complexity:- O(N x 2^N) to keep all the subsets of length NN since each of the NN elements could be present or absent.
Approach 2:
Example
Java
import java.io.*;
import java.util.*;
class GFG {
static List<List<Integer> > subsets( int [] nums)
{
List<List<Integer> > output = new ArrayList<>();
int n = nums.length;
int size = 1 << n;
for ( int i = 0 ; i < size; i++) {
List<Integer> curr = new ArrayList<>();
for ( int j = 0 ; j < n; j++) {
if (((i >> j) & 1 ) == 1 ) {
curr.add(nums[j]);
}
}
output.add(curr);
}
return output;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 };
List<List<Integer> > output = subsets(arr);
System.out.println(output);
}
}
|
Output
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Share your thoughts in the comments
Please Login to comment...