Find all subsets of a given set in Java

Problem: Find all subsets of a given set.
输入: 
S = {a,b,c}
输出:
{},{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c}, 

The total number of subsets of any given set is equal to 2^ (the number of elements in the set). If we notice carefully, it is nothing but a binary number from 0 to 7, which can be displayed as follows:

000 {}
001 {a}
010 {b}
011 {a, b}
100 {c}
101 {a, c}
110 {b, c}
111 {a, b, c}

Starting from the right, the 1 at the i-th position means that the i-th element of the set exists, and 0 means that the element does not exist. Therefore, all we have to do is generate binary numbers from 0 to 2^n – 1, where n is the length of the collection or the number of elements in the collection.

//A Java program to print all subsets of a set 

class Main {
	// Print all subsets of given set[]
	static void printSubsets(char set[]) {
		int n = set.length;

		// Run a loop for printing all 2^n
		// subsets one by one
		for (int i = 0; i < (1 << n); i++) {
			System.out.print(1 << n);
			System.out.print("{ ");

			// Print current subset
			for (int j = 0; j < n; j++)

				// (1<<j) is a number with jth bit 1
				// so when we 'and' them with the
				// subset number we get which numbers
				// are present in the subset and which
				// are not
				if ((i & (1 << j)) > 0)
					System.out.print(set[j] + " ");

			System.out.println("}");
		}
	}

	// Driver code
	public static void main(String[] args) {
		char set[] = { 'a', 'b', 'c' };
		printSubsets(set);
	}
}

<<: Left shift operator, num << 1, is equivalent to num multiplied by 2. In the above code, 1<< n, shifting 1 to the left by n bits is equivalent to 2 to the power of n

>>: Right shift operator, num >> 1, which is equivalent to dividing num by 2

>>>: unsigned right shift, ignoring the sign bit, and the space bits are filled with 0

 

Output:

{ }
{ a }
{ b }
{ a b }
{ c }
{ a c }
{ b c }
{ a b c }

Guess you like

Origin blog.csdn.net/allway2/article/details/114866586