본문 바로가기


카테고리 없음

부분집합 구하기

by worldforest 2020. 2. 20.
//부분집합 구하는 방법

public class SubSetTest {
	public static void main(String[] args) {
		int[] A = { 1, 2, 3, 4, 5 };
		for (int i = 0; i < 1 << A.length; i++) {
			for (int j = 0; j < A.length; j++) {
				if ((i & (1 << j)) != 0) {
					System.out.print(A[j] + " ");
				}
			}
			System.out.println();
		}
	}
}

 

import java.util.ArrayList;

public class SubSetTest2 {
	public static void main(String[] args) {
		int[] A = { 1, 2, 3, 4, 5 };
		ArrayList<Integer> list = new ArrayList<>();
		int cnt = 0;
		for (int i = 0; i < 1 << A.length; i++) {
			int tot = 0;
			int num = 0;
			for (int j = 0; j < A.length; j++) {
				if ((i & (1 << j)) != 0) {
					tot += A[j];
					list.add(A[j]);
					num += (i & (1 << j));
				}
			}
//			System.out.println(tot);// 부분집합의 합
//			합이 10인 부분집합의 개수 =cnt
			if (tot == 10) {
				cnt++;
				System.out.println("합이 " + tot + "인 " + num + "번째 부분집합  : " + list);
			}
			list.clear();
		}
		System.out.println(cnt);
	}
}

 

public class SubSetTest4 {
	public static void main(String[] args) {
		int[] A = { 1, 2, 3, 4, 5 };
		int cnt = 0;
		for (int i = 0; i < 1 << A.length; i++) {
			int tot = 0;
			for (int j = 0; j < A.length; j++) {
				if ((i & (1 << j)) != 0) {
					System.out.print((i | (1 << j)) + " ");
					// 이렇게 했을 때 같은 값이 나오는 것을 부분집합으로 만들었구나
				}
			}
			System.out.println();
		}
	}
}
반응형

댓글