반응형
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
만들 수 있는 모든 조건을 순회하면서 조건에 맞는 정답 개수를 찾도록 만들면 된다.
dfs, bfs를 사용할 수도 있지만, 이 방식이 좀더 직관적이었다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(numbers, target): | |
answer = 0 | |
value = 0 | |
stack = [0] | |
for idx, number in enumerate(numbers,1): | |
temp = [] | |
while stack: | |
operator = stack.pop() | |
## 모든 숫자를 다 써서 타겟 넘버에 도달할 수 있는 경우 | |
if operator + number == target and idx == len(numbers): | |
answer += 1 | |
if operator - number == target and idx == len(numbers): | |
answer += 1 | |
temp.append(operator - number) | |
temp.append(operator + number) | |
stack = temp | |
return answer |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] Hackerrank. Flatland Space Station (Easy) (0) | 2025.07.13 |
---|---|
[Python] Hackerrank. Lily's Homework (Medium) (1) | 2025.07.12 |
[Python] 프로그래머스. 2021 카카오 인턴 - 표 편집 (Level 3) (0) | 2021.07.24 |
[Python] 프로그래머스. 2021 카카오 인턴 - 거리두기 확인하기 (Level 2) (0) | 2021.07.12 |
[Python] 프로그래머스. 2021 카카오 인턴 - 숫자 문자열과 영단어 (Level 1) (0) | 2021.07.09 |