재귀, 백트래킹 (Recursion, Backtracking)
백준 15650 N과 M (2)
ssam..
2020. 5. 3. 20:36
문제 링크: https://www.acmicpc.net/problem/15650
15650번: N과 M (2)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해야 한다.
www.acmicpc.net
조합 (combination)을 출력하는 문제이다.
예를 들어 n = 4, m = 2인 경우에
1 2, 1 3, 1 4, 2 3, 2 4, 3 4와 같이 총 4C2 = 6가지 경우를 출력해야 한다.
순열에서와 같이 이미 사용했는지 여부를 표시할수 있는 used 배열이 필요가 없다.
start라는 변수가 하나 추가되어있는데, start보다 큰 숫자가 더 뒤의 index에서 나올수가 절대로 없기 때문이다.
따라서 a배열의 idx칸에 들어갈 숫자를 결정할때는 순열처럼 1부터 n까지 훑는것이 아니라, start부터 훑으면 된다.
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
|
#include <bits/stdc++.h>
using namespace std;
int n, m, a[10];
void solve(int start, int idx) {
if(idx == m) {
for(int i = 0; i < m; i++)
cout << a[i] << ' ';
cout << '\n';
return;
}
for(int i = start; i <= n; i++) {
a[idx] = i;
solve(i + 1, idx + 1);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
solve(1, 0);
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
위코드는 모든 경우의수를 탐색하기 때문에 시간복잡도가 O(n!)이지만, 아래코드는 각 숫자들을 포함할지 안할지 결정하면서 진행하므로 시간복잡도가 O(2^n)인 코드로서, 더 빠르다.
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
|
#include <bits/stdc++.h>
using namespace std;
int n, m, a[10];
void solve(int start, int idx) {
if(idx == m) {
for(int i = 0; i < m; i++)
cout << a[i] << ' ';
cout << '\n';
return;
}
if(start > n) return;
a[idx] = start;
solve(start + 1, idx + 1);
solve(start + 1, idx);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
solve(1, 0);
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|