알고리즘/백준
[백준] N과M(10)
728x90
반응형
LinkedHashSet을 사용해 순서 보장되는 Set사용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
private static StringBuilder sb = new StringBuilder();
private static int[] element;
private static int[] arr;
private static boolean[] visit;
private static Set<String> set = new LinkedHashSet<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
element = new int[n];
arr = new int[m];
visit = new boolean[n];
line = br.readLine();
st = new StringTokenizer(line);
for (int i = 0; i < element.length; i++) {
element[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(element);
bt(n, m, 0, 0);
for (String s : set) {
sb.append(s).append("\n");
}
System.out.println(sb);
}
private static void bt(int n, int m, int depth, int start) {
if (depth == m) {
for (int i : arr) {
sb.append(i + " ");
}
set.add(sb.toString());
sb.setLength(0);
return;
}
for (int i = start; i < element.length; i++) {
if (!visit[i]) {
visit[i] = true;
arr[depth] = element[i];
bt(n, m, depth + 1, i);
visit[i] = false;
}
}
}
}
728x90
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2644. 촌수계산 (2) | 2023.11.28 |
---|---|
[백준] 2667. 단지번호붙이기 (1) | 2023.11.27 |
[백준] N과M(9) (0) | 2023.04.11 |
[백준] N과M(8) (0) | 2023.04.10 |
[백준] N과M(7) (0) | 2023.04.10 |
댓글