
https://www.acmicpc.net/problem/15665
void bt(int n, int m, int depth, int *sequence, int *nums) {
if (depth == m) {
for (int i = 0; i < m; i++)
printf("%d ", sequence[i]);
printf("\n");
return;
}
int before = 0;
for (int i = 0; i < n; i++) {
if (before != nums[i]) {
sequence[depth] = nums[i];
before = nums[i];
bt(n, m, depth + 1, sequence, nums);
}
}
}
기본적인 bt 함수를 사용하되, 이전 문제들처럼 연속으로 중복된 수열이 출력되는 것을 방지하기 위해 before 변수를 사용했다.
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return *(int *)a - *(int *)b;
}
void bt(int n, int m, int depth, int *sequence, int *nums) {
if (depth == m) {
for (int i = 0; i < m; i++)
printf("%d ", sequence[i]);
printf("\n");
return;
}
int before = 0;
for (int i = 0; i < n; i++) {
if (before != nums[i]) {
sequence[depth] = nums[i];
before = nums[i];
bt(n, m, depth + 1, sequence, nums);
}
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
int *sequence = (int *)malloc(sizeof(int) * m);
int *nums = (int *)malloc(sizeof(int) * n);
for (int i = 0; i < n; i++)
scanf("%d", &nums[i]);
qsort(nums, n, sizeof(int), compare);
bt(n, m, 0, sequence, nums);
free(sequence);
free(nums);
return 0;
}