반응형
💻 Problem
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
- 1부터 N까지 자연수 중에서 M개를 고른 수열
- 같은 수를 여러 번 골라도 된다.
- 고른 수열은 비내림차순이어야 한다.
- 길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK-1 ≤ AK를 만족하면, 비내림차순이라고 한다.
💡 Approach
중복 조합 기본 문제이다.
itertools를 활용해서 푸는 방법과 직접 구현하는 방법 두 가지로 풀어보았다.
✏️ Solution (itertools)
import sys
from itertools import combinations_with_replacement
input = sys.stdin.readline
N, M = map(int, input().split())
print('\n'.join(' '.join(map(str, p)) for p in combinations_with_replacement(range(1, N + 1), M)))
✏️ Solution (직접 구현)
import sys
input = sys.stdin.readline
def combination(start, depth):
if depth == M:
print(*path)
return
for i in range(start, N + 1):
path[depth] = i
combination(i, depth + 1)
N, M = map(int, input().split())
selected = [False] * (N + 1)
path = [0] * M
combination(1, 0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15655번: N과 M (6) (Silver 3) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15654번: N과 M (5) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15651번: N과 M (3) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15650번: N과 M (2) (Silver 3) (0) | 2025.08.16 |