[BaekJoon] 15664번 - N과 M (10) [Java][C++]
[BaekJoon] 15664번 - N과 M (10) [Java][C++]
1. 문제 풀이
$N$ 개의 자연수 중 길이가 $M$ 인 조합을 모두 구하는 문제로 재귀를 활용해서 구하면 된다. 이때 중복되는 조합은 출력하지 않아야 하는데 이는 prev 변수에 최근에 담은 수를 저장하고 반복문 내에서 동일한 수면 넘어가주면 된다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.io.*;
import java.util.*;
public class Main {
static StringBuilder sb = new StringBuilder();
static int N;
static int M;
static int[] arr;
static int[] sel;
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());
arr = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
sel = new int[M];
dfs(0, 0);
System.out.println(sb);
}
static void dfs(int idx, int selIdx) {
if (selIdx == M) {
for (int x : sel) {
sb.append(x).append(" ");
}
sb.append("\n");
return;
}
int prev = 0;
for (int i = idx; i < N; i++) {
if (arr[i] == prev) continue;
prev = sel[selIdx] = arr[i];
dfs(i + 1, selIdx + 1);
}
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <bits/stdc++.h>
using namespace std;
int n, m;
int arr[8];
int sel[8];
void dfs(int idx, int selIdx) {
if (selIdx == m) {
for (int i = 0; i < m; i++) {
cout << sel[i] << ' ';
}
cout << '\n';
return;
}
int prev = 0;
for (int i = idx; i < n; i++) {
if (arr[i] == prev) continue;
prev = sel[selIdx] = arr[i];
dfs(i + 1, selIdx + 1);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> arr[i];
sort(arr, arr + n);
dfs(0, 0);
}
This post is licensed under CC BY 4.0 by the author.