반응형
💻 Problem
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다.
- N개의 자연수 중에서 M개를 고른 수열
- 같은 수를 여러 번 골라도 된다.
💡 Approach
입력받은 num 리스트에서 M개의 원소를 뽑는다. (중복 순열)
✏️ Solution (itertools)
import sys
from itertools import product
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 product(num, repeat=M)))
✏️ Solution (직접 구현)
import sys
input = sys.stdin.readline
def permutation(depth):
if depth == M:
print(*path)
return
for i in range(N):
path[depth] = num[i]
permutation(depth + 1)
N, M = map(int, input().split())
num = sorted(map(int, input().split()))
path = [0] * M
permutation(0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15663번: N과 M (9) (Silver 2) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15657번: N과 M (8) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15655번: N과 M (6) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15654번: N과 M (5) (Silver 3) (0) | 2025.08.16 |