arr에 depth에 맞는 값을 담아서 dfs가 depth만큼 돌면 arr를 출력하면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution15649 {
static int N, M;
static int[] arr;
static boolean[] visited;
public static void main(String[] args) throws IOException {
//4 2
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new int[M];
visited = new boolean[N+1];
dfs(0);
}
static void dfs(int depth) {
if(depth == M) {
for(int a : arr) {
System.out.print(a + " ");
}
System.out.println();
return;
}
for(int i = 1; i < N+1; i++) {
if(!visited[i]) {
visited[i] = true;
arr[depth] = i;
dfs(depth+1);
visited[i] = false;
}
}
}
}