알고리즘/백트래킹

백준 15655번 : N과 M (6) java

LDY3838 2022. 6. 22. 15:14
반응형

이 문제는 입력 받은 배열을 정렬한 후 자신 이후의 인덱스에 있는 자료들을 M개 만큼 출력하는 문제입니다.

이 문제를 해결하기 위해서는 재귀적으로 함수를 불러오면서 불러온 횟수가 M번이 되면 출력하면 됩니다.

코드를 보시면 쉽게 이해하실 수 있으실 겁니다.

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

public class Main {
    static int N, M;
    static int[] data;
    static int[] answer;
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        data = new int[N];
        answer = new int[M];

        st = new StringTokenizer(br.readLine());
        for(int i = 0; i<N; i++)
            data[i] = Integer.parseInt(st.nextToken());

        Arrays.sort(data);

        backTracking(0, 0);
    }

    static void backTracking(int idx, int count){
        if(count == M){
            for(int i = 0; i<M; i++)
                System.out.print(answer[i]+" ");
            System.out.println();
            return;
        }

        for(int i = idx; i<N; i++){
            answer[count] = data[i];
            backTracking(i+1, count+1);
        }
    }
}
반응형