競技プログラミングで必要になったので、ビット全探索のシンプルな演習をしてみた。
ビット全探索練習
class Main {
public static void main(String[] args) {
// 集合{a,b,c}の部分集合を列挙する
String[] s= {"a","b","c"};
//要素数
int n=3;
//2^nパターンを探索
for(int i=0 ;i< (1<<n) ; i++) {
String sub="";
//iパターン目の各要素をチェック
for(int j=0 ;j<n;j++) {
//iの2進数、末尾からj番目のbitが1かどうかを判定
//例)i=4(100)⇒ j=0,1ならfalse、j=2ならtrue
//trueの場合要素を格納する
if((1 & i>>j)==1) sub += s[j];
}
System.out.println("{"+sub+"}");
}
}
}