반응형
💻 Problem
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다.
- N개의 자연수 중에서 M개를 고른 수열
💡 Approach
입력받은 num 리스트에서 M개의 원소를 뽑는다. (순열)
✏️ Solution (itertools)
import sys
from itertools import permutations
input = sys.stdin.readline
N, M = map(int, input().split())
num = sorted(list(map(int, input().split())))
print('\n'.join(' '.join(map(str, p)) for p in permutations(num, M)))
✏️ Solution (직접 구현)
import sys
input = sys.stdin.readline
def permutation(depth):
if depth == M:
print(*path)
return
for i in range(N):
if selected[i]:
continue
selected[i] = True
path.append(num[i])
permutation(depth + 1)
path.pop()
selected[i] = False
N, M = map(int, input().split())
num = sorted(map(int, input().split()))
selected = [False] * N
path = []
permutation(0)
반응형
'Algorithm > 백준 (BOJ)' 카테고리의 다른 글
[Python] 백준/BOJ 15656번: N과 M (7) (Silver 3) (0) | 2025.08.16 |
---|---|
[Python] 백준/BOJ 15655번: N과 M (6) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15652번: N과 M (4) (Silver 3) (0) | 2025.08.16 |
[Python] 백준/BOJ 15651번: N과 M (3) (Silver 3) (0) | 2025.08.16 |