answer = 0
def dfs(dest, dest_len, n, total, sign, target):
if sign == '+':
total += dest[n]
elif sign == '-':
total -= dest[n]
n = n + 1
if n == dest_len:
if total == target:
global answer
answer += 1
return
dfs(dest, dest_len, n, total, '+', target)
dfs(dest, dest_len, n, total, '-', target)
def solution(numbers, target):
dest_len = len(numbers)
dfs(numbers, dest_len, 0, 0, '+', target)
dfs(numbers, dest_len, 0, 0, '-', target)
return answer
answer = 0
def dfs(dest, dest_len, n, total, target):
if n == dest_len:
if total == target:
global answer
answer += 1
return
dfs(dest, dest_len, n + 1, total+dest[n], target)
dfs(dest, dest_len, n + 1, total-dest[n], target)
def solution(numbers, target):
dest_len = len(numbers)
dfs(numbers, dest_len, 1, numbers[0], target)
dfs(numbers, dest_len, 1, -numbers[0], target)
return answer
def solution(numbers, target):
if not numbers and target == 0 :
return 1
elif not numbers:
return 0
else:
return solution(numbers[1:], target-numbers[0]) + solution(numbers[1:], target+numbers[0])
다음과 같이 궁극적으로 간소화할 수 있다.