Post

combination

🙋‍♂️ 들어가며

조합을 볼까?

1
2
n = 10
r = 5

${}{n}C{r}$ = 252



여기서 조합을 구현할 수 있는 방법은 다음과 같다

  1. 백트랙킹
  2. 비스마스킹

그런데 2개는 연산횟수의 차이가 있다.

백트랙킹의 경우 252가지

비트마스킹은 $2^{10}$ -> 1024

그래서 백트랙킹 조합이 훨씬 낫다.



백트랙킹 조합 작동방식

Desktop View

이런식으로 조합의 갯수를 구한다.

Desktop View


✅ 코드

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
package boj;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import java.util.Arrays;


public class Main {
	static int n;
	static int r;
	static int[] possible_code; 
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		n = 10;
		r = 5;
		possible_code = new int[r];
		
		comb(1,0);
	}
	
	
	static void comb(int start, int depth) {
		// 최대 깊이 도달시
		if (depth == r) {
			System.out.println(Arrays.toString(possible_code));
			return;
		}
		
		// 아직 못 도달했다면
		for (int i = start; i < n+1; i++) {
			possible_code[depth] = i;
			comb(i+1, depth+1);
		}
		
	}
	
		
	
}




이 코드를 보고 이해가 안간다면 아래 글을 참고하자

arr[0] = 7

여기서부터 사실상 나가리 -> 다 조합해도 5개가 안된다

그 외에 arr[0] = 10인 경우에는

comb(11, 1) 인데 다음 재귀부터는

for (int 11 = start, i < 11; i++)

이라서 사실상 arr[1]부터는 들어올 수가 없다

This post is licensed under CC BY 4.0 by the author.

Trending Tags

도움이 필요하면
나를 눌러 구리🐻
챗봇
너굴
bot
어서와 구리 ʕ ·ᴥ·ʔ
무엇이 필요하셔 구리?

Trending Tags

도움이 필요하면
나를 눌러 구리🐻
챗봇
너굴
bot
어서와 구리 ʕ ·ᴥ·ʔ
무엇이 필요하셔 구리?