Algorithm
백준
N과 M (2)

N과 M (2)

https://www.acmicpc.net/problem/15650 (opens in a new tab)

풀이

ℹ️

join 함수는 리스트의 요소사이에 특정 문자를 넣어서 문자열로 합치는 함수입니다.

N, M = map(int, input().split())
nums = [i for i in range(1, N + 1)]
 
def backtrack(curr) :
  if len(curr) == M :
    print(" ".join(map(str, curr)))
    return
  for n in nums :
    if n not in curr :
      curr.append(n)
      backtrack(curr)
      curr.pop()
 
backtrack(curr=[])

Java 풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class boj_15650 {
    static StringBuilder sb = new StringBuilder();
    static int n, m;
    static boolean[] visit;
    static int[] arr;
 
 
    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());
 
        visit = new boolean[n];
        arr = new int[m];
        dfs(0,0);
        System.out.println(sb);
    }
 
    private static void dfs(int depth, int start) {
        if (depth == m) {
            for (int val : arr) {
                sb.append(val).append(" ");
            }
            sb.append("\n");
            return;
        }
 
        for (int i = start; i < n; i++) {
            if (!visit[i]) {
                visit[i] = true;
                arr[depth] = i + 1;
                dfs(depth + 1, i+1);
                visit[i] = false;
            }
        }
    }
}