자기개발👨‍💻/코딩 알고리즘

Python 언어로 조합 구현! (combi함수안쓰고!)

천숭이 2023. 12. 3. 21:30

입력 변수 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]