m1ndy5's coding blog

99클럽 코테 스터디 11일차 TIL bfs/dfs : 프로그래머스 LV.2 타겟넘버 with Python 본문

알고리즘 with python/알고리즘 스터디

99클럽 코테 스터디 11일차 TIL bfs/dfs : 프로그래머스 LV.2 타겟넘버 with Python

정민됴 2024. 5. 30. 22:04

https://school.programmers.co.kr/learn/courses/30/lessons/43165

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제는 위쪽에서!

 

def solution(numbers, target):
    answer = [0]
    
    def dfs(cur, i):
        if i == len(numbers):
            if cur == target:
                answer[0] += 1
            return
        
        dfs(cur+numbers[i], i+1)
        dfs(cur-numbers[i], i+1)
            
    dfs(0, 0)
    
    return answer[0]

 

재귀함수를 사용해서 문제를 풀었다.

cur은 현재까지 더하거나 뺀 숫자들의 합이고 numbers에 있는 숫자들을 더하고 빼면서 모든 숫자들을 더하고 뺐을 때의 결과값이 타겟값과 같다면 1을 올려주는 형식으로 풀었다.