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