본문 바로가기
알고리즘/백트래킹

[백준 풀이_Java] 15652 N과 M (4)

by happyhelen 2024. 2. 16.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    static int N;
    static int M;
    static int[] arrAnswer;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        N = Integer.parseInt(input[0]);
        M = Integer.parseInt(input[1]);
        arrAnswer = new int[M];
        recur( 1, 0);
    }


    static void recur(int start, int cnt){

        if(cnt == M){ // M개라면

            for(int one : arrAnswer){
                System.out.print(one + " ");
            }
            System.out.println();
            return;
        }

        for(int i=start; i<=N; i++){
            arrAnswer[cnt] = i; // 인덱스를 cnt로 활용
            recur(i, cnt + 1); // 중복 허용이라서 i+1 대신 i
        }
    }
}