반응형
💻 Problem
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다.
- N개의 자연수 중에서 M개를 고른 수열
- 고른 수열은 오름차순이어야 한다.
💡 Approach
입력받은 num 리스트에서 순서 없이 M개의 원소를 뽑는다. (조합)
✏️ Solution (itertools)
import sys
from itertools import combinations
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(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):
if N - i + 1 < M - depth:
break
path.append(num[i])
combination(i + 1, depth + 1)
path.pop()
N, M = map(int, input().split())
num = sorted(map(int, input().split()))
selected = [False] * N
path = []
combination(0, 0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15657번: N과 M (8) (Silver 3) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15656번: N과 M (7) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15654번: N과 M (5) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15652번: N과 M (4) (Silver 3) (0) | 2025.08.16 |