[BaekJoon] 15649번 - N과 M (1) [Java][C++]
[BaekJoon] 15649번 - N과 M (1) [Java][C++]
1. 문제 풀이
$1$ 부터 $N$ 까지의 수 중 길이가 $M$ 인 순열을 모두 구하는 문제로 재귀를 활용해서 방문 체크를 하며 구하면 된다.
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
import java.io.*;
import java.util.*;
public class Main {
static StringBuilder sb = new StringBuilder();
static int N;
static int M;
static int[] sel;
static boolean[] visited;
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());
sel = new int[M];
visited = new boolean[1 + N];
dfs(0);
System.out.println(sb);
}
static void dfs(int selIdx) {
if (selIdx == M) {
for (int x : sel) {
sb.append(x).append(" ");
}
sb.append("\n");
return;
}
for (int i = 1; i <= N; i++) {
if (visited[i]) continue;
sel[selIdx] = i;
visited[i] = true;
dfs(selIdx + 1);
visited[i] = false;
}
}
}
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
#include <bits/stdc++.h>
using namespace std;
int n, m;
int sel[8];
bool visited[1 + 8];
void dfs(int selIdx) {
if (selIdx == m) {
for (int i = 0; i < m; i++) {
cout << sel[i] << ' ';
}
cout << '\n';
return;
}
for (int i = 1; i <= n; i++) {
if (visited[i]) continue;
sel[selIdx] = i;
visited[i] = true;
dfs(selIdx + 1);
visited[i] = false;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
dfs(0);
}
This post is licensed under CC BY 4.0 by the author.