<문제>
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
<입력>
첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)
<출력>
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.
수열은 사전 순으로 증가하는 순서로 출력해야 한다.
찾아보니 Python 내부 함수 itertools의 combinations_with_replacement라는 것이 중복조합을 계산해주는 함수라는 것을 알게됨.
from itertools import combinations_with_replacement
N, M = map(int, input().split())
C_r = combinations_with_replacement(range(1, N+1), M) # iter(tuple)
for i in C_r:
print(' '.join(map(str, i))) # tuple -> str
🔗참고
https://juhee-maeng.tistory.com/91
combinations_with_replacement(=중복조합)
combinations_with_replacement(반복 가능한 객체, r)from itertools import combinations_with_replacement for cwr in combinations_with_replacement([1,2,3,4], 2): print(cwr, end=" ") # (1, 1) (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 3) (3, 4) (4, 4)
🔗백준 - N과 M (4)
https://www.acmicpc.net/problem/15652