본문 바로가기

재귀, 백트래킹 (Recursion, Backtracking)

백준 10974 모든 순열

문제 링크: https://www.acmicpc.net/problem/10974

 

10974번: 모든 순열

N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오.

www.acmicpc.net

말그대로 모든 순열을 순서대로 출력하는 문제이다.

두가지 방법으로 풀었는데, 하나는 재귀함수를 사용하였고 다른하나는 next_permutation 함수를 사용하였다.

아래코드는 재귀함수를 사용한 코드이다.

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
#include <bits/stdc++.h>
using namespace std;
 
int n, a[10];
bool used[10];
 
void solve(int idx) {
    if(idx == n) {
        for(int i = 0; i < n; i++)
            cout << a[i] << ' ';
        cout << '\n';
        return;
    }
 
    for(int i = 1; i <= n; i++) {
        if(!used[i]) {
            used[i] = true;
            a[idx] = i;
            solve(idx + 1);
            used[i] = false;
        }
    }
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> n;
    solve(0);
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

아래코드는 next_permutation함수를 이용한 코드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <bits/stdc++.h>
using namespace std;
 
int n, a[10];
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> n;
    for(int i = 0; i < n; i++) a[i] = i + 1;
    do {
        for(int i = 0; i < n; i++)
            cout << a[i] << ' ';
        cout << '\n';
    } while(next_permutation(a, a + n));
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

'재귀, 백트래킹 (Recursion, Backtracking)' 카테고리의 다른 글

백준 10971 외판원 순회 2  (0) 2020.05.04
백준 10819 차이를 최대로  (0) 2020.05.04
백준 10973 이전 순열  (0) 2020.05.04
백준 10972 다음 순열  (0) 2020.05.04
백준 15657 N과 M (8)  (0) 2020.05.04