PS/Python

[백준] 15649 - N과 M (1) (파이썬, Python)

w00se 2021. 3. 27. 22:41

[문제 출처]

www.acmicpc.net/problem/15649

 

15649번: N과 M (1)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net


기본적인 순열을 구현하는 문제이다.

 

여러 문제를 풀어 오면서 순열을 이용하는 문제를 여러 번 만났지만 직접 순열을 구현한 적은 없었다.

(python은 itertools 라이브러리를 이용하면 편리하게 순열을 계산할 수 있다.)

 

이 문제를 만나 처음으로 순열을 구현해봤는데 쉽지 않았다.

다른 자료를 참고해서 공부한 후 구현한 코드는 아래와 같다.


전체 코드

import sys

def permutation(data, n):
    res = []
    
    if n == 1:
        res = [[e] for e in data]

    elif n >= 2:
        for t in data:
            excluded = data[:]
            excluded.remove(t)

            excludedPermutation = permutation(excluded, n-1)

            for case in excludedPermutation:
                res.append([t]+case)

    return res
    
N, M = map(int, sys.stdin.readline().split(" "))

results = permutation(list(range(1, N+1)), M)

for res in results:
    print(" ".join(map(str, res)))