이 풀이의 작동 원리는
이 링크 로 보면 편하게 이해할 수 있다. 이 코드는 breadth-first search(
BFS) 알고리즘을 사용한다. BFS는 그래프 수준별로 탐색하는 그래프 탐색 알고리즘의 일종으로, 루트 노드에서 시작하여 다음 수준으로 진행하기 전에 각 수준에서 모든 노드를 확장한다.
이 코드의 시간 복잡도은 그래프의 노드 수와 그래프의 분기 계수에 따라 달라지게 된다. 이 경우 그래프는 숫자 시퀀스로 표시되며 분기 계수는 2가 된다(각 단계에서 대기열에 두 개의 새 노드를 추가하기 때문에). 따라서 이 코드의 시간 복잡도는 $O(2^n)$이며, 여기서 n은 숫자 배열의 길이이다.
deftarget_number(numbers,target):# Initialize a counter for the number of waysways=0# Recursively try all possible combinations of numbers# and check if they add up to the target numberdeffind_ways(numbers,index,cur_sum,target):nonlocalways# If we have reached the end of the array,# check if the current sum is equal to the targetifindex==len(numbers):ifcur_sum==target:ways+=1return# Try adding the current number to the sumfind_ways(numbers,index+1,cur_sum+numbers[index],target)# Try subtracting the current number from the sumfind_ways(numbers,index+1,cur_sum-numbers[index],target)# Start the recursive search from the first number in the arrayfind_ways(numbers,0,0,target)# Return the number of waysreturnways
This solution uses a recursive function find_ways that tries all possible combinations of numbers in the array and checks if their sum is equal to the target number. At each step, the function has two options: either add the current number to the sum, or subtract it. When the end of the array is reached, the current sum is compared to the target number, and if they are equal, the counter ways is incremented.
이 솔루션은 배열에서 가능한 모든 숫자 조합을 시도하고 합이 목표 숫자와 동일한지 확인하는 재귀 함수 find_ways를 사용합니다. 각 단계에서 함수에는 두 가지 옵션이 있습니다. 즉, 현재 숫자를 합계에 추가하거나 숫자를 빼거나 둘 중 하나입니다. 배열의 끝에 도달하면 현재 합계가 목표 숫자와 비교되고, 둘이 같으면 ways 가 증가합니다.