Search
 
SCRIPT & CODE EXAMPLE
 

CPP

How to generate all subsets of a given set in Java?

import java.util.List;
import java.util.ArrayList;
public class GeneratingSubsets {
	/*
	 * This code generates all subsets of a given
	 * set having n elements.
	 * 
	 * Time complexity: O(n2^n)
	 * Space complexity: O(2^n)
	 * 
	 */
	public static void main(String[] args) {
		int[] arr = { 1, 8, 7 };
		List<List<Integer>> subsets = generateSubsets(arr);
		/*
		 * Below prints:
		 * [[], [1], [7], [1, 7], [8], [1, 8], [7, 8], [1, 7, 8],
		 * [9], [1, 9], [7, 9], [1, 7, 9], [8, 9], [1, 8, 9], [7,8, 9],
		 * [1, 7, 8, 9]]
		 */
		System.out.println(subsets);
	}

	// Below function generates subsets of array
	private static List<List<Integer>> generateSubsets(int[] arr) {
		// Idea is to count on binary representation of array
		// size. Then, consider all binary representations
		// having 1 valued bits using positions of these bits
		// as indexes into array.
		List<List<Integer>> subsets = new ArrayList<>();
		int[] set = { 1, 7, 8, 9 };
		int n = set.length;
		for (int b = 0; b < (1 << n); b++) {
			List<Integer> subset = new ArrayList<Integer>();
			for (int i = 0; i < n; i++) {
				if ((b & (1 << i)) != 0) {
					subset.add(set[i]);
				}
			}
			subsets.add(subset);
		}
		return subsets;
	}
}
Comment

How to generate all the possible subsets of a set ?

#include<bits/stdc++.h>
using namespace std;

int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);

  int n;
  cin>>n;
 vector<char>v(n);
 for(int i=0;i<n;i++){
     cin>>v[i];
 }
cout<<"All Possible subset:
";
 for(int i=0;i<(1<<n);i++){
     for(int j=0;j<n;j++){
        if(i&(1<<j)){
             cout<<v[j]<<" ";
        }
     }
     cout<<'
';
 }

return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: Program to find GCD or HCF of two numbers c++ 
Cpp :: valid parentheses in cpp 
Cpp :: ex: cpp 
Cpp :: public method 
Cpp :: split text c++ 
Cpp :: c++ power of two 
Cpp :: binary to decimal 
Cpp :: even and odd numbers 1 to 100 
Cpp :: c++ itoa 
Cpp :: binary multiplication 
Cpp :: c++ visual studio 
Cpp :: how togreper 
Cpp :: summation of numbers using function 
Cpp :: c ++ The output should be (abc),(def),(ghw) 
Cpp :: Common elements gfg in c++ 
Cpp :: the amount of input is unknown 
Cpp :: How do you count the occurrence of a given character in a string? c++ 
Cpp :: ejemplo 
Cpp :: c++ throe 
Cpp :: c++ program to convert fahrenheit to kelvin 
Cpp :: function and function prototype. 
Cpp :: KL/wweiok#L['.[- 
Cpp :: overload operator object function call 
Cpp :: CPPDEVELOPER 
Cpp :: powershell script query mssql windows authentication 
Cpp :: qt get wireless interface name 
Cpp :: c++ multiple if conditions 
Cpp :: gcc compile multi thread 
Cpp :: c++ comments 
Cpp :: Tricky Subset Problem 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =