반응형
💻 Problem
자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
- 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열
💡 Approach
순열 기본 문제이다.
itertools를 활용해서 푸는 방법과 직접 구현하는 방법 두 가지로 풀어보았다.
✏️ Solution (itertools)
import sys
from itertools import permutations
input = sys.stdin.readline
N, M = map(int, input().split())
print('\n'.join(' '.join(map(str, p)) for p in permutations(range(1, N + 1), M)))
✏️ Solution (직접 구현)
import sys
input = sys.stdin.readline
def permutation(depth):
# 1. 기저 조건
# 모든 원소를 선택함
if depth == M:
print(*path)
return
# 2. 전처리 로직
# 아직 다 선택하지 않음
for i in range(1, N + 1):
# 이미 선택한 원소는 패스
if selected[i]:
continue
selected[i] = True
path.append(i)
# 3. 재귀 호출
permutation(depth + 1)
# 4. 후처리 로직
# 사용 다 했으면 되돌리기
path.pop()
selected[i] = False
N, M = map(int, input().split())
selected = [False] * (N + 1)
path = []
permutation(0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15651번: N과 M (3) (Silver 3) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15650번: N과 M (2) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 24523번: 내 뒤에 나와 다른 수 (Silver 2) (2) | 2025.08.15 |
[Python] 백준/BOJ 27970번: OX (Silver 1) (0) | 2025.08.10 |