169. N과 M(10)

아현·2021년 7월 9일
0

Algorithm

목록 보기
173/400

백준




Python


n, m = map(int, input().split())
data = list(map(int, input().split()))

data.sort()
visited = [False] * n
out = []

def recur(k, idx):
    if k == m:
        print(' '.join(map(str, out)))
        return
    overlap = 0
    for i in range(idx, n):
   		#if !(k > 0 and out[-1] > data[i]): continue; 

      if not visited[i] and overlap != data[i]:
            visited[i] = True
            out.append(data[i])
            overlap = data[i]
            recur(k+1, i+1)
            visited[i] = False
            out.pop()

recur(0, 0)



C++


#include <cstdio>
#include <algorithm>
using namespace std;

int n, m, a[8], answer[8];
bool used[8];

void recur(int k) {
    if (k == m) {
        for (int i = 0 ; i < m ; i++) {
            printf("%d ", answer[i]);
        }
        printf("\n");
        return;
    }
    int prev = 0;
    for (int i = 0 ; i < n ; i++) {
        if (used[i]) continue;
        if (k > 0 && answer[k - 1] > a[i]) continue;
        if(prev != a[i]){
            used[i] = true;
            answer[k] = a[i];
            prev = a[i];
            recur(k + 1);
            used[i] = false;
        
        }
        
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0 ; i < n ; i++) scanf("%d", &a[i]);
    sort(a, a + n);
    recur(0);
}

profile
For the sake of someone who studies computer science

0개의 댓글