기타/코딩테스트

(코테) 백준_15649_N과 M (1) 백트레킹 수

불광동 물주먹 2025. 5. 19. 17:55

 

 

 

 

 

 

 

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

public class Backjun_15649 {

    static int N, M;
    static int[] result;
    static boolean[] visited;

    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());

        visited = new boolean[N];
        result = new int[M];

        dfs(0);
    }

    public static void dfs(int depth) {
        if (depth == M) {
            for (int i : result) {
                System.out.print(i + " ");
            }
            System.out.println();
            return;
        }

        for (int i = 0; i < N; i++) {
            if (visited[i]) continue;

            visited[i] = true;
            result[depth] = i + 1;  // 1부터 시작하는 숫자
            dfs(depth + 1);
            visited[i] = false;
        }
    }
}