sugang
sugang'study
sugang
전체 방문자
오늘
어제
  • 분류 전체보기
    • [OS]
    • [취업정보]
    • [Server]
    • [Algorithm]
    • [Database]
    • [MyTravel]
    • [Network]

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • n

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
sugang

sugang'study

[Algorithm]

백트래킹- 조합 구현

2023. 5. 23. 23:38

문제

1이상 N 이하의 숫자 중 M 개의 숫자를 골라 만들 수 있는 모든 조합을 구해주는 프로그램을 작성

코드

n,m=map(int,input().split())

combination = []
def print_combination():
    for elem in combination:
        print(elem, end = " ")
    
    print()

def find_combination (cnt,last_num):
    if cnt==m:
        print_combination()
        return

    #뽑을 수 있는 원소의 후보들 탐색
    for i in range(last_num+1,n+1):
        combination.append(i)
        find_combination(cnt+1,i)
        combination.pop()


# 가능한 범위를 순회하며 해당 숫자가 
# 조합의 첫번째 숫자일 때를 탐색
for i in range(1, n + 1):
    combination.append(i)
    find_combination(1, i)
    combination.pop()

ex ) 5,3

i=1 일때 backtraking으로 pop과 append 를 반복하며 

1 

1 2 

1 2 3

1 2 

1 2 4 

1 2 

1 2 5

...

이러한 순서로 진행된다. 

'[Algorithm]' 카테고리의 다른 글

SortedDict  (0) 2023.05.26
hashmap 두 수의 합  (0) 2023.05.26
시뮬레이션 - 1차원 폭발 게임  (0) 2023.05.14
[탐색] 전략 추려내기 - ABC 줄세우기  (0) 2023.05.10
완전탐색 - 최대최소차  (0) 2023.05.08
    '[Algorithm]' 카테고리의 다른 글
    • SortedDict
    • hashmap 두 수의 합
    • 시뮬레이션 - 1차원 폭발 게임
    • [탐색] 전략 추려내기 - ABC 줄세우기
    sugang
    sugang

    티스토리툴바