2일차. 조합 알고리즘

HAHAING·2025년 5월 27일

코딩 테스트

목록 보기
2/30
post-thumbnail

10개 중에서 5개의 조합을 구하는 알고리즘 -
방법 1. for 문을 사용해구함 -> 5개의 for문이 필요함.
방법 2. 재귀 함수를 사용한다.

N = 10 #10개의 수 중에서 
R = 3 #3개를 선택할 조합

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
choose = [] # 조합 저장할 공간 

def combination(index, level): 
	#base line
	if level == R: #3개가 되면 choose처리 
    	print(choose)
        return 
        
    #3개가 모일때까지 recursive 
    for i in range(index,N):  #10까지 반복
   		choose.append(lst[i]) # 인덱스가 i인 원소 선택 
        combination(i+1, level+1) #
        choose.pop() 
combination(0,0)
            
profile
따뜻한 시선으로 세상을 변화시키는 데이터사이언티스트

0개의 댓글