입력 변수 n, arr
arr는 n*2개의 크기를 가지고 있다고 하자.
import sys
n = 2
arr = [1,2,3,4]
numbers = []
def print_combination(arr):
for i in arr :
print(i, end=' ')
print()
# curr_idx : 탐색의 정도, 배열을 모두 탐색했을 때 종료해야 하므로
# curr_idx == 배열의 크기 가 재귀함수의 종료조건. (성공/실패 모두 포함)
# 그리고 선택된 배열의 크기를 나타내는 cnt -> numbers 배열에 append 할 때마다 cnt+1 되고 있으므로.
# 따라서 cnt의 크기는 몇 개를 선택했느냐, 조합 선택 여부를 살펴보는 조건. (성공일때만)
def make_combination(curr_idx, cnt):
# 종료 조건
if curr_idx == 2*n:
# 조합 완성되는 조건
if cnt == 2:
print_combination(numbers)
return
numbers.append(arr[curr_idx])
make_combination(curr_idx+1, cnt+1)
numbers.pop()
make_combination(curr_idx+1, cnt)
make_combination(0,0)
주석 참고 :)
n = 3
def find_min(color, cnt):
if color == n :
if cnt==n-1 :
print(numbers)
return
numbers.append(color)
find_min(color+1, cnt+1)
numbers.pop()
find_min(color+1, cnt)
find_min(0, 0)
출력 :
[0, 1]
[0, 2]
[1, 2]
'자기개발👨💻 > 코딩 알고리즘' 카테고리의 다른 글
파이썬 알면 좋은 내용! (3) | 2023.12.07 |
---|---|
DFS, BFS (0) | 2023.12.06 |
[C++] 순열부터 조합까지 직접 구현해보기 (작성중) (0) | 2023.12.05 |
특정 m개중에 n개 고르기 (조합) (0) | 2023.12.03 |
[Python] 트로미노 - 이중배열탐색 (0) | 2023.11.30 |
[Python] 대각선으로 숫자 채우기 - 이중배열 (0) | 2023.11.29 |