반응형
💻 Problem
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
- 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열
- 고른 수열은 오름차순이어야 한다.
💡 Approach
조합 기본 문제이다.
itertools를 활용해서 푸는 방법과 직접 구현하는 방법 두 가지로 풀어보았다.
✏️ Solution (itertools)
import sys
from itertools import combinations
input = sys.stdin.readline
N, M = map(int, input().split())
print('\n'.join(' '.join(map(str, p)) for p in combinations(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):
if N - i + 1 < M - depth:
break
path.append(i)
combination(i + 1, depth + 1)
path.pop()
N, M = map(int, input().split())
selected = [False] * (N + 1)
path = []
combination(1, 0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15652번: N과 M (4) (Silver 3) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15651번: N과 M (3) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15649번: N과 M (1) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 24523번: 내 뒤에 나와 다른 수 (Silver 2) (2) | 2025.08.15 |