subset
๐โโ๏ธ ๋ค์ด๊ฐ๋ฉฐ
์ด๋ฒ ์๊ฐ์๋ subset์ ๊ตฌํ๋ ๋ฐฉ๋ฒ์ 2๊ฐ๋ก ์์๋ณผ ๊ฒ์ด๋ค
back-tracking vs bit-masking
๋ฐฐ์ด์ด ์ด๋ ๊ฒ ์๋ค๊ณ ๊ฐ์ ํ์
์๋ Java ์ฝ๋๋ combination ๊ด์ ์์ ์ ๊ทผํ ํต์ฌ ํ์ด์ ๋๋ค. ์ ๋ ฅ ์กฐ๊ฑด๊ณผ ์๊ฐยท๊ณต๊ฐ ๋ณต์ก๋๋ฅผ ํจ๊ป ๊ณ ๋ คํ์ฌ ๋ถํ์ํ ์ฐ์ฐ์ ์ค์ด๋ ๋ฐฉํฅ์ผ๋ก ์ค๊ณํ์ต๋๋ค.
1
int[] arr = {1, 6, 13, 9, 27, 100};
์ ๊ตฌํ์ subset์ ์ ์ฝ ์กฐ๊ฑด์ ๋ง์กฑํ๋๋ก ์๋ฃ๊ตฌ์กฐ ์ ํ๊ณผ ๋ฐ๋ณต ๋ฒ์๋ฅผ ์ต์ ํํ ๊ฒฐ๊ณผ์ ๋๋ค.
๋ฐฑํธ๋ํน์ผ๋ก ๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ์ด ์งํ๋ ๊ฒ์ด๋ค
1
2
3
4
5
[]
/ \
[1] []
/ \ / \
[1,6] [1] [6] []
2๊ฐ์ง๋ก ๋๋๊ธฐ์ ์๊ฐ๋ณต์ก๋ -> O(2^N)
โ ์ฝ๋ (back-tracking)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package boj;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
public class Main {
static int N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = {1, 6, 13, 9, 27, 100};
N = arr.length;
for (int i = 0; i < N; i++) {
int[] subset = new int[N];
subset[0] = arr[i];
comb(i+1, arr, subset, 1);
}
}
static void comb(int depth, int[] arr, int[] subset, int size) {
// 1. ์ต๋ ๊น์ด ๋๋ฌ์ ์ถ๋ ฅ
if (depth == N) {
int[] answer = new int[size];
for (int i = 0; i < size; i++) {
answer[i] = subset[i];
}
System.out.println(Arrays.toString(answer));
return;
}
// 2. ์์ง ์ต๋ ๊น์ด ๋๋ฌ ๋ชปํ๋ค๋ฉด
subset[size] = arr[depth];
// 2-1. ์ ํ
comb(depth+1, arr, subset, size+1);
// 2-2. ๋ฏธ์ ํ
comb(depth+1, arr, subset, size);
}
}
}
๋ค์์ ๋น์ค๋ง์คํน์ด๋ค
์๊ฐ๋ณต์ก๋๋ O(N^2)
์ค์ ๋ก n <= 20 ์ผ๋ ๋ง์ด ์ฌ์ฉํ๋ค
์ฝ๋๋ ๋ค์๊ณผ ๊ฐ๋ค
โ ์ฝ๋ (bit-masking)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package boj;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = {1, 6, 13, 9, 27, 100};
int total = 1 << arr.length;
int n = arr.length;
for (int bit = 0; bit < total; bit++) {
int[] subset = new int[n];
int size = 0;
for (int mask = 0; mask < n; mask++) {
if ( (bit & (1<<mask) ) != 0 ) {
subset[size] = arr[mask];
size++;
}
}
// ์ถ๋ ฅ
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = subset[i];
}
System.out.println(Arrays.toString(result));
}
}
}
This post is licensed under CC BY 4.0 by the author.
