n = len(numbers)
dfs(depth, ...):
# base case
if depth == (n-1):
return
def dfs(depth, case, total):
.
.
.
########### HERE ###########
# plus
dfs(0, 0, 0)
# minus
dfs(0, 1, 0)
############################
이를 유념해서 코드를 짜보자!
def solution(numbers, target):
global count
count = 0
n = len(numbers)
def dfs(depth, case, total):
global count
cur_v = numbers[depth]
if case == 0:
total = total+cur_v
elif case == 1:
total = total-cur_v
if depth == (n-1):
if total == target:
count+=1
return
#next_v = numbers[depth+1]
dfs(depth+1, 0, total)
dfs(depth+1, 1, total)
# plus
dfs(0, 0, 0)
# minus
dfs(0, 1, 0)
return count
# bfs
from collections import deque
def solution(numbers, target):
global count
n = len(numbers)
cur_dep = 0
count = 0
queue = deque()
queue.append((0, numbers[0]))
queue.append((0, -numbers[0]))
while queue:
cur_dep, cur_tot = queue.popleft()
if cur_dep == n-1:
if cur_tot == target:
count+=1
# 다음 step: numbers의 idx 빠져나가면 안됌
if cur_dep+1<n:
# plus
queue.append((cur_dep+1, cur_tot + numbers[cur_dep+1]))
# minus
queue.append((cur_dep+1, cur_tot - numbers[cur_dep+1]))
return count
if __name__ == "__main__":
numbers = [1, 1, 1, 1, 1]
target = 3
answer = solution(numbers, target)
print("answer: ", answer)
answer: 5