- N과 M (1) : 중복 수열 X / 숫자 중복 X
- N과 M (2) : 중복 수열 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 == 현재 수열 길이
// start == 어느 숫자부터 시작할건지
void suyeol(int cnt, int start) {
// 길이가 m인 수열을 다 만들었다
if (cnt == m) {
for (int i = 0; i < m; i++)
cout << ans[i] << " ";
cout << "\n";
return;
}
// 오름차순이므로 앞서 방문했던 숫자들을 더 이상 볼 필요가 없다
for (int i = start; i <= n; i++) {
if (!visited[i]) {
visited[i] = true;
ans[cnt] = i;
suyeol(cnt + 1, i);
visited[i] = false;
}
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
suyeol(0, 1);
return 0;
}
#include <iostream>
#include <algorithm>
#define MAX_NUM 10
using namespace std;
int arr[MAX_NUM];
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++)
arr[i] = (i < m ? 0 : 1);
do {
for (int i = 0; i < n; i++)
if(arr[i] == 0)
cout << i + 1 << " ";
cout << "\n";
} while (next_permutation(arr, arr + n));
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, 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] = i+1
suyeol(cnt+1, i)
visited[i] = False
suyeol(0, 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 |
| [백준 15649] N과 M (1) (C++/Python) (0) | 2020.12.07 |