조합의 경우의 수 출력(DFS)

Changwook Yang·2023년 2월 5일

알고리즘 연습

목록 보기
23/41

N, M을 입력했을떄
nCm을 출력하라

ex) 6 4

출력)
0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5

import java.util.Scanner;

public class Main {

    static int n;
    static int m;
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        m = scanner.nextInt();

        combination = new int[m];
        int level = 0;
        int start = 0;
        DFS(level, start);
    }

    static int[] combination;
    private static void DFS(int level, int start) {
        if (level == m) { // m개 뽑았을때
            for (int value : combination) {
                System.out.print(value + " ");
            }
            System.out.println();
        } else {
            for (int i = start; i < n; i++) {
                // 시작점부터 n개까지 뽑아내야함
                combination[level] = i;
                DFS(level + 1, i + 1);
            }
        }

    }


}
profile
멋있는 백엔드 개발자 / 꾸준히 의미있게!

0개의 댓글