Python 문제풀이/프로그래머스&해커랭크

타겟 넘버 (DFS/BFS) / nonlocal

hjc_ 2022. 4. 1. 17:54

 

링크

 

 

# global 과 nonlocal 차이 중요!
# 여기서는 def solution 라는 함수에 포함되어있어서 nonlocal로 해야 한다.

def solution(numbers, target):
    answer = 0
    def dfs(index, nsum):
        nonlocal answer
        # 1.탈출 조건
        if index == len(numbers): 
            if nsum == target:
                answer += 1 
                return answer
            else : return 
        
        # 2. 재귀 구현
        dfs(index+1, nsum + numbers[index])
        dfs(index+1, nsum - numbers[index])
        
        
    dfs(0, 0)    
    return answer