반응형
💻 Problem
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다.
- N개의 자연수 중에서 M개를 고른 수열
- 같은 수를 여러 번 골라도 된다.
- 고른 수열은 비내림차순이어야 한다.
- 길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK-1 ≤ AK를 만족하면, 비내림차순이라고 한다.
💡 Approach
입력받은 num 리스트에서 순서 없이 M개의 원소를 뽑는다. (중복 조합)
✏️ Solution (itertools)
import sys
from itertools import combinations_with_replacement
input = sys.stdin.readline
N, M = map(int, input().split())
num = sorted(map(int, input().split()))
print('\n'.join(' '.join(map(str, p)) for p in combinations_with_replacement(num, M)))
✏️ Solution (직접 구현)
import sys
input = sys.stdin.readline
def combination(start, depth):
if depth == M:
print(*path)
return
for i in range(start, N):
path[depth] = num[i]
combination(i, depth + 1)
N, M = map(int, input().split())
num = sorted(map(int, input().split()))
selected = [False] * (N + 1)
path = [0] * M
combination(0, 0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15664번: N과 M (10) (Silver 2) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15663번: N과 M (9) (Silver 2) (0) | 2025.08.16 |
[Python] 백준/BOJ 15656번: N과 M (7) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15655번: N과 M (6) (Silver 3) (0) | 2025.08.16 |