코딩테스트

백준 15655: N과 M (6) [JAVA]

stdio.han 2024. 5. 8. 02:02

https://www.acmicpc.net/problem/15655

[난이도]

- Silver 3

 

[알고리즘]

- 백트래킹

 

[코드]

import java.io.*;
import java.util.*;

public class Main {
    static int N, M;
    static boolean[] checked;
    static int[] arr, tmp;
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        checked = new boolean[N];
        arr = new int[N];
        tmp = new int[N];

        st = new StringTokenizer(br.readLine(), " ");
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr); // 오름차순 정렬
        backTracking(0, 0);
        bw.flush();
    }

    static void backTracking(int depth, int start) throws Exception {
        if (depth == M) { // depth 가 M이 될때까지 실행
            for (int i = 0; i < M; i++) {
                bw.write(tmp[i] + " ");
            }
            bw.write("\n");
            return;
        }
        for (int i = start; i < N; i++) {
            if (!checked[i]) { // 사용한 숫자 체크
                checked[i] = true;
                tmp[depth] = arr[i];
                backTracking(depth + 1, i);
                checked[i] = false; // 완전탐색을 위해 사용한 숫자는 false
            }
        }
    }
}

[풀이]

매개변수로 depth 말고 start 변수도 추가했다. start 매개변수는 i 로 재귀한다.