Part5.8_완전탐색_부분집합 구하기(DFS)__순열 구하기

Eugenius1st·2022년 1월 24일
0

Python_algorithm

목록 보기
36/83

순열 구하기

내가 생각한 코드

import sys
sys.stdin = open("input.txt", "rt")


def DFS(L):
    global cnt

    if L == m:
        for j in range(m):
            print(a[j], end=" ")
        cnt+=1
        print()
    
                   
    else:
        for i in range(1,n+1):
            if L>0 and a[L-1] == i:
                continue
            else:
                a[L] = i

            DFS(L+1)


if __name__ == "__main__":
    n, m = map(int,input().split()) # 3 2
    a =[0]*m
    cnt = 0
    DFS(0)
    print(cnt)


?? 왜 왜지??

힌트봤다 !!!

중복을 만들지 않도록

check 리스트를 만들어서 확인하라..

import sys
sys.stdin = open("input.txt", "rt")


def DFS(L):
    global cnt

    if L == m:
        for j in range(m):
            print(a[j], end=" ")
        cnt+=1
        print()                
    else:

        for i in range(1,n+1):
            if ch[i]==0:
                ch[i]=1
                a[L] = i
                DFS(L+1)
                ch[i] = 0 # 여기서 되돌려줘야 하는 논리를 알아야 한다!!!!!! 진행상태 중, 이 줄은 back 해서 돌아온 부분이잖아 !!!!
                # ↑↑↑↑여기는 함수가 종료되고 한단계 전으로 돌아온 부분이기 때문에 0으로 초기화해줘도 되는거지 !! 다음 for문을 위해서..
            else:
                continue

if __name__ == "__main__":
    n, m = map(int,input().split()) # 3 2
    a =[0]*m
    ch = [0]*(n+1)
    cnt = 0

    DFS(0)
    print(cnt)

0으로 초기화 해주는 부분에 대한 이해 !! 사고력 길러라..

profile
최강 프론트엔드 개발자가 되고싶은 안유진 입니다

0개의 댓글