- N과 M (1) : 중복 수열 X / 숫자 중복 X
C++)
#include <iostream>
#include <algorithm>
#define MAX_NUM 10
using namespace std;
int n, m;
int ans[MAX_NUM];
bool visited[MAX_NUM];
// cnt == 현재 수열의 길이
void suyeol(int cnt) {
// m개 수열을 만들었다
if (cnt == m) {
for (int i = 0; i < m; i++)
cout << ans[i] << " ";
cout << "\n";
return;
}
// 만드는 중
for (int i = 0; i < n; i++) {
// 수열에 들어가지 않은 숫자를 만났다
if (!visited[i]) {
visited[i] = true;
ans[cnt] =i + 1;
suyeol(cnt + 1);
visited[i] = false;
}
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
suyeol(0);
return 0;
}
Python)
import sys
read = sys.stdin.readline
n, m = map(int, read().rstrip().split())
ans = [0] * m
visited = [False] * n
def suyeol(cnt):
if cnt == m:
print(' ' .join(map(str, ans)))
return
for i in range(n):
if not visited[i]:
visited[i] = True
ans[cnt] = i+1
suyeol(cnt+1)
visited[i] = False
suyeol(0)'백준 2 > 백트래킹' 카테고리의 다른 글
| [백준 15655] N과 M(6) (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 |
| [백준 15650] N과 M(2) (C++/Python) (0) | 2020.12.07 |