반응형

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
StringBuilder sb = new StringBuilder();
int[] num;
int[] inputNumber;
boolean[] check;
public void solution() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
StringTokenizer stt = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
num = new int[m];
check = new boolean[n];
inputNumber = new int[n];
for(int i = 0; i<n; i++){
inputNumber[i] = Integer.parseInt(stt.nextToken());
}
Arrays.sort(inputNumber);
dfs(n, m, 0);
System.out.println(sb);
}
public void dfs(int n, int m, int depth){
if(depth==m){
for(int a : num){
sb.append(a).append(" ");
}
sb.append("\n");
return;
}
for(int i = 0; i<n; i++){
if(!check[i]){
check[i] = true;
num[depth] = inputNumber[i];
dfs(n,m, depth+1);
check[i] = false;
}
}
}
public static void main(String args[]) throws IOException {
new Main().solution();
}
}
DFS와 백트래킹을 활용한다. 주어진 숫자를 배열에 저장하고, 숫자를 크기대로 정렬한 다음 인덱스로 그 값을 순차적으로 사용한다. 방문한 곳을 제외하고 순차적으로 접근하기 위해 방문 체크를 해주고 탐색을 진행한다.
반응형
'개발 > 알고리즘' 카테고리의 다른 글
백준 15656번 : N과 M (7) (0) | 2023.01.06 |
---|---|
백준 15655번 : N과 M (6) (0) | 2023.01.06 |
백준 15652번 : N과 M (4) (0) | 2023.01.04 |
백준 15651번 : N과 M (3) (0) | 2023.01.04 |
백준 15650번 : N과 M (2) (0) | 2023.01.04 |