-
백트래킹(Backtracking) / N과 M(1)Problem Solving/BOJ 2023. 7. 1. 16:24
용어에 대한 정리가 필요하여 작성.
백트래킹이란?
- 모든 경우의 수를 전부 고려하는 알고리즘. 단 탐색 중에 유망하지 않은 경우에는 이전 단계로 돌아가서 다른 후보 탐색.
완전 탐색의 일종.
완전탐색(Bruteforce)과 백트래킹은 무엇이 다른가?
- 완전탐색은 모든 경우의 수를 대입. 유망성을 검사하지 않음.
간단한 백트래킹 문제 하나.
https://www.acmicpc.net/problem/15649
15649번: N과 M (1)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
경우의 수는 nPr = n! / (n-r)! 이 된다.
(n = n, m = r)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#include<iostream>#include<cstring>#include<vector>#include<queue>#include<unordered_map>#include<map>#include<algorithm>#include<string>#include<cmath>#include<stack>#define INF 1e9using namespace std;using lld = long long int;using pii = pair<int, int>;bool visited[10];int a[10];int n, m;void solve(int dep) {if(dep == m) {for(int i=0; i<m; i++) {cout << a[i] << " ";}cout << "\n";return;}for(int i=1; i<=n; i++) {if(visited[i]) continue;visited[i] = true;a[dep] = i;solve(dep+1);visited[i] = false;}return;}int main() {ios::sync_with_stdio(false);cin.tie(NULL);cin >> n >> m;memset(visited, 0, sizeof(visited));solve(0);return 0;}cs 'Problem Solving > BOJ' 카테고리의 다른 글
중복 조합(combinations with repetition) / N과 M(4) (0) 2023.07.01 백준 BOJ 15650 N과 M(2) (0) 2023.07.01 외판원 순회 (Traveling Salesman Problem) (0) 2023.06.20 LIS (Longest Increasing Subsequence) (0) 2023.06.17 백준 BOJ 11025 요세푸스 문제 3 (1) 2023.01.22