[백준/C] 15665 - N과 M (11)

orangesnail·2024년 8월 11일

백준

목록 보기
9/169
post-thumbnail

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;
}
profile
초보입니다. 피드백 환영합니다 😗

0개의 댓글