問題:特定のセットのすべてのサブセットを検索します。
输入:
S = {a,b,c}
输出:
{},{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c},
任意のセットのサブセットの総数は、2 ^(セット内の要素の数)に等しくなります。注意深く気付くと、それは0から7までの2進数に過ぎず、次のように表示できます。
000 | {} |
001 | {a} |
010 | {b} |
011 | {a、b} |
100 | {c} |
101 | {交流} |
110 | {b、c} |
111 | {a、b、c} |
右から順に、i番目の位置にある1は、セットのi番目の要素が存在することを意味し、0は要素が存在しないことを意味します。したがって、0から2 ^ n – 1までの2進数を生成するだけです。ここで、nはコレクションの長さまたはコレクション内の要素の数です。
//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);
}
}
<<:左シフト演算子num << 1は、numに2を掛けることに相当します。上記のコード1 << nでは、1を左にnビットシフトすると、2のn乗に相当します。
>>:右シフト演算子、num >> 1、これはnumを2で割ることに相当します
>>>:符号なし右シフト、符号ビットを無視し、スペースビットは0で埋められます
出力:
{ }
{ a }
{ b }
{ a b }
{ c }
{ a c }
{ b c }
{ a b c }