프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
프로그래머스 타겟 넘버 파이썬 16173
더보기


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

사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.
제한사항)
주어지는 숫자의 개수는 2개 이상 20개 이하입니다.
각 숫자는 1 이상 50 이하인 자연수입니다.
타겟 넘버는 1 이상 1000 이하인 자연수입니다.
입출력 예)


📌 문제 풀이

이런 식으로, numbers에 담긴 각 요소들의 +, -를 합하여 target의 값을 구해나가야 한다.
재귀함수를 이용하여 DFS의 풀이 방식으로 문제를 풀어보았다.
DFS(Depth-First Search), 깊은 부분을 우선적으로 탐색하는 알고리즘
1. numbers의 요소들을 모두 +, - 할 때까지 재귀함수는 반복된다.
2. +인 경우와, -인 경우를 각각 DFS로 실행시켜주면 된다.
3. 모든 numbers 요소들을 사용하고 난 후, target과의 값과 동일할 때, count를 1 증가시킨다.
✅ [CODE]
cnt = 0
def dfs(numbers, target, current, idx):
global cnt
if idx == len(numbers):
if current == target:
cnt += 1
return
dfs(numbers, target, current + numbers[idx], idx + 1)
dfs(numbers, target, current - numbers[idx], idx + 1)
def solution(numbers, target):
dfs(numbers, target, 0, 0)
return cnt
반응형