조합이란 서로 다른 n개중에 r개를 선택하는 경우의 수를 의미합니다.
조합은 순서를 고려하지 않습니다. ( [1,2,3] == [2,3,1] )
import java.io.*;
import java.util.*;
public class test {
static int N, R; // N개 중에 R개를 선택
static int[] combiArr; // R개의 조합을 담는 배열
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
R = Integer.parseInt(br.readLine());
combiArr = new int[R];
combination(0,1);
}
static void combination(int deep, int num) {
if(deep == R) {
System.out.println(Arrays.toString(combiArr));
return;
}
for(int i=num; i<=N; i++) {
combiArr[deep] = i;
combination(deep+1, i+1);
combiArr[deep] = 0;
}
}
}
[입력-출력 예시]
3개 중에 2개를 고르는 경우 (순서 상관 없고 중복 없이)
3
2
[1, 2]
[1, 3]
[2, 3]