[알고리즘] 조합 / 순열

김제현·2024년 7월 8일
0

알고리즘

목록 보기
12/17

조합

N = 4
R = 3
lst = [1,2,3,4]
choose = []

def combination(index, level):
    if level == R:
        print(choose)
        return
    
    for i in range(index, N):
        choose.append(lst[i])
        combination(i+1, level+1)
        choose.pop()

combination(0,0)
from itertools import combinations

print(list(combinations(lst, 3)))

순열

N = 10
R = 3
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
check = [False] * N # 원소 사용 여부를 체크
# check[k] 가 true 이면 인덱스가 k인 원소가 사용중임을 나타냄.
# check[k] 가 false 이면 인덱스가 k인 원소가 사용중이지 않음을 나타냄.
choose = [] # 나열한 원소를 보관

def permutation(level):
	if level == R:
		# 나열한 R 개의 원소를 출력
		print(choose)
		return

	# for문
	for i in range(0, N):
		if check[i] == True: # 인덱스가 i인 원소가 이미 사용중이라면 continue
			continue

		choose.append(lst[i]) # 인덱스가 i인 원소를 선택(추가) 
		check[i] = True # 인덱스가 i인 원소를 사용하고 있으므로 true로 초기화

		permutation(level+1) # 다음 for 문으로 들어가는 역할

		check[i] = False # 인덱스가 i인 원소의 사용이 끝났으므로 false로 초기화
		choose.pop() # (넣었던) 인덱스가 i인 원소를 제거


permutation(0)

0개의 댓글