1
1

競技プログラミング練習 ビット全探索(Java)

Posted at

競技プログラミングで必要になったので、ビット全探索のシンプルな演習をしてみた。

ビット全探索練習



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+"}");
		}
	}
}
	
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1