<문제>
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
<입력>
첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)
<출력>
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.
수열은 사전 순으로 증가하는 순서로 출력해야 한다.
고민해보다가 어떻게 풀어야할지 감이 잡히지 않아 다른사람의 코드를 보기로 함.
🔗풀이 참고
https://wlstyql.tistory.com/56
1. 이 풀이법은 이해하기 쉽지 않았다.
N, M = map(int, input().split())
visited = [False] * N # 탐사 여부 check
out = [] # 출력 내용
def solve(depth, N, M):
if depth == M: # 탈출 조건
print(' '.join(map(str, out))) # list를 str으로 합쳐 출력
return
for i in range(len(visited)): # 탐사 check 하면서
if not visited[i]: # 탐사 안했다면
visited[i] = True # 탐사 시작(중복 제거)
out.append(i+1) # 탐사 내용
solve(depth+1, N, M) # 깊이 우선 탐색
visited[i] = False # 깊이 탐사 완료
out.pop() # 탐사 내용 제거
solve(0, N, M)
2. Python 내부 함수 itertools의 permutations(중복하지 않는 순열 찾아줌)을 이용한 풀이이다.
from itertools import permutations
N, M = map(int, input().split())
P = permutations(range(1, N+1), M) # iter(tuple)
for i in P:
print(' '.join(map(str, i))) # tuple -> str
🔗참고
https://ourcstory.tistory.com/414
파이썬에서 리스트에 있는 값들의 모든 조합을 구하기 위해서 파이썬 기본 라이브러리인 itertools을 이용하면 쉽게 구할 수 있음.
from itertools import product
from itertools import permutations
from itertools import combinations
permutations
permutations(순열)는 몇 개를 골라 순서를 고려해 나열한 경우의 수를 말함. 즉, 서로 다른 n 개 중 r 개를 골라 순서를 정해 나열하는 가짓수를 의미.items = ['1', '2', '3', '4', '5'] from itertools import permutations list(permutations(items, 2)) # [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '1'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '1'), ('3', '2'), ('3', '4'), ('3', '5'), ('4', '1'), ('4', '2'), ('4', '3'), ('4', '5'), ('5', '1'), ('5', '2'), ('5', '3'), ('5', '4')]
combinations
combinations(조합)는 서로 다른 n개 중에서 r개(n≥r) 취하여 조를 만들 때, 이 하나하나의 조를 n개 중에서 r개 취한 조합이라고 함.items = ['1', '2', '3', '4', '5'] from itertools import combinations list(combinations(items, 2)) # [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]
product
from itertools import product items = [['a', 'b', 'c,'], ['1', '2', '3', '4'], ['!', '@', '#']] list(product(*items)) # [('a', '1', '!'), ('a', '1', '@'), ('a', '1', '#'), ('a', '2', '!'), ('a', '2', '@'), ('a', '2', '#'), ('a', '3', '!'), ('a', '3', '@'), ('a', '3', '#'), ('a', '4', '!'), ('a', '4', '@'), ('a', '4', '#'), ('b', '1', '!'), ('b', '1', '@'), ('b', '1', '#'), ('b', '2', '!'), ('b', '2', '@'), ('b', '2', '#'), ('b', '3', '!'), ('b', '3', '@'), ('b', '3', '#'), ('b', '4', '!'), ('b', '4', '@'), ('b', '4', '#'), ('c,', '1', '!'), ('c,', '1', '@'), ('c,', '1', '#'), ('c,', '2', '!'), ('c,', '2', '@'), ('c,', '2', '#'), ('c,', '3', '!'), ('c,', '3', '@'), ('c,', '3', '#'), ('c,', '4', '!'), ('c,', '4', '@'), ('c,', '4', '#')]
🔗백준 - N과 M (1)
https://www.acmicpc.net/problem/15649