문제 링크
https://programmers.co.kr/learn/courses/30/lessons/43165
코딩테스트 연습 - 타겟 넘버
n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+
programmers.co.kr
풀이
- bfs 사용해서 풀이. ( bfs 연습 좀 해야겠다 )
from collections import deque
def solution(numbers, target):
answer = 0
queue = deque()
# 큐에 더하거나 뺀 결과와 index를 저장
queue.append((0,0))
while queue:
# 더한 결과와 index
result, index = queue.popleft()
# index가 주어진 숫자들의 개수와 같다면 마지막 숫자라는 뜻
if index == len(numbers):
# 최종 결과과 target 숫자와 같은지 비교
if result == target:
# 같다면 방법의 수 + 1
answer +=1
else :
number = numbers[index]
# 더하고 뺀 결과 저장, index + 1
queue.append((result + number, index + 1))
queue.append((result - number, index +1 ))
return answer'개발 > algorithm' 카테고리의 다른 글
| [프로그래머스][level2] 올바른 괄호 -python (0) | 2021.12.28 |
|---|---|
| [프로그래머스][level2] 삼각 달팽이 - python (0) | 2021.12.28 |
| [프로그래머스][level2] 거리두기 확인하기 (0) | 2021.12.28 |
| [프로그래머스][level2] 최댓값과 최솟값 - python (0) | 2021.12.28 |
| [프로그래머스][level2] 배달-python (0) | 2021.12.28 |