[순환] 멱집합(Powerset)
2023. 7. 22. 07:32ㆍ기타(이론)/알고리즘
멱집합
어떤 집합 A에 대하여 A의 모든 부분 집합들로 이루어진 집합을 A의 멱집합이라고 한다.
Mission: S의 멱집합을 출력하라
powerSet(s)
if S is an empty set
print nothing;
else
let t be the first element of S;
find all sudsets of S-{t} by calling powerSet(S-{t});
print the subsets;
print the subsets with adding t;
위 방법은 여러개의 집합들을 return해야 한다.
따라서 Recursion을 이용하면
powerSet(P, S) //S의 멱집합을 구한 후 각각에 집합 P를 합집합하여 출력하라
if S is an empty set
print P;
else
let t be the first element of S;
powerSet(P, S-{t}); //t포함 X
powerSet(P{t}, S-{t}); //t 포함 O
함수로 구현하면
private static char data[]= {'a','b','c','d','e','f'};
private static int n=data.length;
private static boolean [] include = new boolean [n]; //트리상에서 현재 나의 위치를 표현한다.
public static void powerSet(int k) {
if(k==n) { //만약 내 위치가 리프노드라면
for(int i=0;i<n;i++)
if(include[i]) System.out.print(data[i]+" ");
System.out.println();
return;
}
include[k]=false;
powerSet(k+1); //먼저 왼쪽으로 내려갔다가
include[k]=true;
powerSet(k+1); //이번엔 오른쪽으로 내려간다
}
[무료] 영리한 프로그래밍을 위한 알고리즘 강좌 - 인프런 | 강의
영리하게 프로그래밍을 할 수 있기 위한 기본 소양인 '알고리즘'을 배우고 응용하는 방법을 배웁니다., 개발자라면 꼭 알아야 할 알고리즘 입문! [사진] 1. 강의 소개 부경대학교 IT융합응용공학
www.inflearn.com
'기타(이론) > 알고리즘' 카테고리의 다른 글
[Binary Search Tree] (1) | 2024.11.24 |
---|---|
알고리즘의 복잡도 (0) | 2024.10.25 |
T(n) (1) | 2024.10.01 |
[파이썬] Pandas Library (0) | 2023.09.03 |