Algorithm/알아두면 좋은 템플릿 코드

[Combination] 조합 템플릿 코드

생각없이 해도 생각보다 좋다. 2023. 6. 17. 13:07
import java.util.Arrays;
import java.util.Scanner;

/*
    총 개수: N
    뽑는 개수: R
    순열과는 다르게 isSelected를 사용하지 않고, 재귀 내의 반복문의 시작점인 start를 변경해줌으로써 조합 형태의 경우의 수 구현
 */
public class Combination {
    static int N, R, totalCnt;
    static int[] totals, selected;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        R = sc.nextInt();
        totals = new int[N];
        selected = new int[R];
        for (int i = 0; i < N; i++) {
            totals[i] = i+1;
        }

        combi(0, 0);
        System.out.println(totalCnt);
    }

    private static void combi(int cnt, int start) {
        if(cnt == R){
            totalCnt++;
            System.out.println(Arrays.toString(selected));
            return;
        }

        for (int i = start; i < N; i++) {
            selected[cnt] = totals[i];
            combi(cnt +1, i+1);
        }
    }

}