강의

멘토링

로드맵

Inflearn Community Q&A

menthamin6296's profile image
menthamin6296

asked

Introduction to Python Algorithm Problem Solving (Coding Test Preparation)

6. Finding duplicate permutations (DFS)

전역변수 res 를 DFS에 전달해주지 않아도 문제없는 이유가 궁금합니다.

Resolved

Written on

·

266

0

DFS(L, res) 이런식으로 res를 전달해주지 않아도

코드가 잘 돌아가는  이유가 궁금합니다. 

DFS에 res를 전달해주지 않으면 재귀함수가 돌면서

전역변수 res의 값들이 계속 바뀌어서 원하는 값을 출력 못할 것  같은데

DFS를 호출해서 res[L] = i 라는 코드를 만나면 

DFS별로 res배열이 선언되는걸까요?

import sys
sys.stdin=open("input.txt""r")

def DFS(Lres):
    # 종료조건
    if L==M:    
        for i in range(M):
            print(res[i], end=" ")
        print()
        return
    else:
        # 트리전개 3 방향으로
        for i in range(1, N+1):
            res[L]=i
            DFS(L+1, res)

if __name__=="__main__":
    N, M=map(intinput().split())
    res=[0]*M
    DFS(0, res)

python코테 준비 같이 해요!

Answer 1

1

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

res라는 리스트는 전역으로 한 번만 선언됩니다.

하나의 리스트를 레벨변수인 L을 리스트의 인덱스 변수로 사용해 L값이 커졌다 작아졌다 하면서 새로운 값을 res리스트에 넣어주는 것입니다.

menthamin6296's profile image
menthamin6296

asked

Ask a question