문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/43165
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
def solution(numbers, target):
cnt = 0
size = len(numbers)
def dfs(depth,total):
if depth == size:
if total == target:
nonlocal cnt
cnt += 1
return
dfs(depth+1,total+numbers[depth])
dfs(depth+1,total-numbers[depth])
dfs(0,0)
return cnt
풀이
- DFS로 해결했다.
- depth가 len(numbers) 되면, 그때까지의 total이 target과 같을 경우 cnt를 1 증가시켜준다.
- 주의할 점은 뎁스가 증가할때, 둘 중 하나를 더하고, 안 더하고가 아닌, 둘다 더하거나 빼야 된다는 점이다.
'👨🏻💻알고리즘 > 프로그래머스' 카테고리의 다른 글
| [프로그래머스] Lv2. 연속 부분 수열의 합의 개수 (0) | 2023.01.23 |
|---|---|
| [프로그래머스] Lv2. k진수에서 소수 개수 구하기 (0) | 2023.01.22 |
| [프로그래머스] Lv2. 귤 고르기 (0) | 2023.01.22 |
| [프로그래머스] Lv2. 뉴스 클러스터링 (0) | 2023.01.22 |
| [프로그래머스] Lv2. 프린터 (0) | 2023.01.22 |