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

[백준 풀이_Java] 73646155 N과 M (3) (실버 3)

by happyhelen 2024. 2. 19.

 

 

 

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;

    static StringBuilder sb = new StringBuilder();

    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(0);
        
        sb.delete(sb.length() - 1, sb.length()); // 마지막 개행은 지운다
        System.out.println(sb);
    }


    static void recur(int cnt){
    
        if(cnt == M){ // M개라면
        
            for(int one : arrAnswer){
            //    System.out.print(one + " "); // 처음에는 sout으로 했는데 시간초과나서 sb로 바꿈
                sb.append(one).append(" ");
            }
            sb.append("\n");
            return;
        }

        for(int i=1; i<=N; i++){
        
            arrAnswer[cnt] = i;
            recur(cnt + 1);
        }
    }
}