파이썬 알고리즘 문제 풀이

[프로그래머스] Lv2. 타겟 넘버 파이썬 DFS, BFS

gogi masidda 2024. 2. 2. 17:00
  • 타겟 넘버
문제 설명

n개의 음이 아닌 정수들이 있습니다. 이 정수들을 순서를 바꾸지 않고 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다.

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.

 

BFS

def solution(numbers, target):
    leaves = [0]
    count = 0
    for num in numbers:
        nodes = []
        
        for leaf in leaves:
            nodes.append(leaf+num)
            nodes.append(leaf-num)
        leaves = nodes
    for leaf in leaves:
        if leaf == target:
            count+=1 
    return count

 

DFS

count = 0

def dfs(index, numbers, target, value):
    global count
    if index == len(numbers) and value == target:
        count += 1
        return
    elif index == len(numbers):
        return
    else:
        dfs(index+1, numbers, target, value + numbers[index])
        dfs(index+1, numbers, target, value - numbers[index])

def solution(numbers, target):
    dfs(0, numbers, target, 0)
    return count

dfs는 leaf까지 가서 값을 확인하면 되므로 값을 저장해둘 필요가 없다.

728x90