- N과 M (1) : 중복 수열 X / 숫자 중복 X
- N과 M (2) : 중복 수열 X / 숫자 중복 X / 오름차순
- N과 M (3) : 중복 수열 X / 숫자 중복 O
- N과 M (4) : 중복 수열 X / 숫자 중복 O / 비내림차순
~~아래부터는 사용자로부터 직접 입력받음~~
- N과 M (5) : 중복 수열 X / 사전 증가순
- N과 M (6) : 중복 수열 X / 사전 증가순 / 오름차순
C++)
#include <iostream>
#include <algorithm>
#include <vector>
#define MAX_NUM 10
using namespace std;
int n, m;
vector<int> v;
int ans[MAX_NUM]; // 정답 가진 배열
bool visited[MAX_NUM]; // 방문 여부
// cnt == 현재 수열 길이
// cur == 탐색 시작 위치
void suyeol(int cnt, int cur) {
if (cnt == m) {
for (int i = 0; i < m; i++)
cout << ans[i] << " ";
cout << "\n";
return;
}
for (int i = cur; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
ans[cnt] = v.at(i);
suyeol(cnt + 1, i+1);
visited[i] = false;
}
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
int temp;
for (int i = 0; i < n; i++) {
cin >> temp;
v.push_back(temp);
}
// 사전순이니까 오름차순 정렬
sort(v.begin(), v.end());
suyeol(0, 0);
return 0;
}
Python)
import sys
read = sys.stdin.readline
n, m = map(int, read().rstrip().split())
ans = [0] * m
visited = [False] * n
arr = list(map(int, read().rstrip().split()))
def suyeol(cnt, cur):
if cnt == m:
print(' ' .join(map(str, ans)))
return
for i in range(cur, n):
if not visited[i]:
visited[i] = True
ans[cnt] = arr[i]
suyeol(cnt+1, i+1)
visited[i] = False
arr.sort()
suyeol(0, 0)'백준 2 > 백트래킹' 카테고리의 다른 글
| [백준 15657] N과 M(8) (C++/Python) (0) | 2020.12.07 |
|---|---|
| [백준 15656] N과 M(7) (C++/Python) (0) | 2020.12.07 |
| [백준 15654] N과 M(5) (C++/Python) (0) | 2020.12.07 |
| [백준 15652] N과 M(4) (C++/Python) (0) | 2020.12.07 |
| [백준 15651] N과 M(3) (C++/Python) (0) | 2020.12.07 |