레슨 1 · 파이썬 알고리즘 실버
**완전탐색(Brute Force)**은 가능한 모든 경우의 수를 직접 확인하는 방법이에요. 구현이 단순하고 확실하지만, 경우의 수가 많아지면 시간 초과가 날 수 있어요.
n개 중 r개를 순서 있게 뽑는 경우의 수 = nPr
from itertools import permutations
arr = [1, 2, 3, 4, 5]
for perm in permutations(arr, 3): # 5P3 = 60가지
print(perm)
# (1,2,3), (1,2,4), ...
import math
print(math.perm(5, 3)) # 60n개 중 r개를 순서 없이 뽑는 경우의 수 = nCr
from itertools import combinations
arr = [1, 2, 3, 4, 5]
for comb in combinations(arr, 3): # 5C3 = 10가지
print(comb)
# (1,2,3), (1,2,4), (1,2,5), ...
import math
print(math.comb(5, 3)) # 10from itertools import product, combinations_with_replacement
arr = [1, 2, 3]
# 중복 순열: 3개에서 2개를 중복 허용해서 순서 있게
for p in product(arr, repeat=2):
print(p) # (1,1), (1,2), (1,3), (2,1), ...
# 중복 조합: 3개에서 2개를 중복 허용해서 순서 없게
for c in combinations_with_replacement(arr, 2):
print(c) # (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)| 함수 | 설명 | 개수 |
|---|---|---|
permutations(arr, r) | 순열 (순서 O, 중복 X) | nPr |
combinations(arr, r) | 조합 (순서 X, 중복 X) | nCr |
product(arr, repeat=r) | 중복 순열 (순서 O, 중복 O) | nʳ |
combinations_with_replacement(arr,r) | 중복 조합 | n+r-1Cr |