티스토리 뷰
문제출처 - 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+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘
programmers.co.kr
answer = 0
def dfs(numbers, target, idx, total):
global answer
if idx == len(numbers):
if target == total:
answer += 1
return
dfs(numbers, target, idx + 1, total + numbers[idx])
dfs(numbers, target, idx + 1, total - numbers[idx])
def solution(numbers, target):
global answer
dfs(numbers, target, 0, 0)
return answer
설명
재귀 형태의 깊이우선탐색(DFS)을 사용해 풀었다.
answer은 전역변수로 선언했다.
numbers의 값들을 +/- 로 나눠 이진트리 형태로 만든 다음 모든 경우를 다 따져봐서 target이랑 일치하는 값을 찾는다.
'ALGORITHM > 프로그래머스' 카테고리의 다른 글
[Python]프로그래머스 - 올바른 괄호(level2) (0) | 2020.02.25 |
---|---|
[Python]프로그래머스 - 이상한 문자 만들기(level1) (0) | 2020.02.25 |
[Python][완전탐색] 프로그래머스 - 카펫(Level2) (0) | 2020.02.23 |
[Python][완전탐색] 프로그래머스 - 숫자야구(Level2) (0) | 2020.02.22 |
[Python][완전탐색] 프로그래머스 - 소수찾기(Level2) (0) | 2020.02.22 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Permutation
- hash
- 2019 Kakao Blind Recruitment
- 구현
- 백준
- 문자열처리
- programmers
- 파이썬
- 재귀
- 코딩테스트
- 괄호
- SWExpert
- 딕셔너리
- 문자열
- 완전탐색
- 2020 KAKAO BLIND RECRUITMENT
- Python
- 우선순위큐
- 정렬
- SW Expert
- 해시
- C++
- combination
- 스택
- 순열
- BOJ
- left join
- 힙
- dictionary
- 프로그래머스
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함