본문 바로가기

Coding test

[백준/15654/파이썬] N과 M (5)


소스코드 ( itertools 사용 )

from itertools import permutations
n,m = list(map(int,input().split()))
s = list(map(int,input().split()))

tmp = sorted(list(permutations(s,m)))
for i in tmp:
  print(' '.join(map(str,i)))

소스코드 ( 재귀 사용 )

n,m = list(map(int,input().split()))
seq = list(map(int,input().split()))
seq = sorted(seq)
s = []
def dfs(start):
    if len(s) == m:     
        print(' '.join(map(str,s)))
        return
    for i in seq:
      if i not in s:
        s.append(i)
        dfs(i)
        s.pop()
dfs(1)


생각

1번은 itertool을 사용하고 정렬 한 번을 사용하였고

2번은 정렬하고 재귀를 돌며 알고리즘을 작성했는데

시간은 1번이 더 적게 수행했고 메모리는 2번이 더 적게 잡아먹었음을 알 수 있었다.

알고리즘에 대한 설명은  -> https://codekunst.tistory.com/49

'Coding test' 카테고리의 다른 글

[백준/18290/파이썬] NM과 K (1)  (0) 2023.02.27
[백준/15655/파이썬] N과 M (6)  (0) 2023.02.23
[백준/15652/파이썬] N과 M (4)  (0) 2023.02.20
[백준/15651/파이썬] N과 M (3)  (0) 2023.02.19
[백준/15650/파이썬] N과 M (2)  (0) 2023.02.18