[프로그래머스] 타겟 넘버 (python)
문제
풀이
- global 사용하지 않은 풀이
def solution(numbers, target):
global ans
# arr = numbers
# num = target
ans = 0
dfs(numbers, target, 0, 0)
return ans
def dfs(numbers, target, _sum, idx):
global ans
if idx == len(numbers):
if _sum == target:
ans += 1
return
# print(idx)
dfs(numbers, target, _sum + numbers[idx], idx+1)
dfs(numbers, target, _sum - numbers[idx], idx+1)
print(solution([1, 1, 1, 1, 1], 3))
- global을 사용하여 parameter를 넘기지 않는 코드
def solution(numbers, target):
global ans, arr, num
arr = numbers
num = target
ans = 0
dfs(0, 0)
return ans
def dfs(_sum, idx):
global ans, arr, num
if idx == len(arr):
if _sum == num:
ans += 1
return
dfs(_sum + arr[idx], idx+1)
dfs(_sum - arr[idx], idx+1)
print(solution([1, 1, 1, 1, 1], 3))
Leave a comment