Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.

Commit 04cfa29

Browse files
임지수Woo-Yeol
authored andcommitted
Create 타겟 넘버 jisu.py
1 parent e82b1ad commit 04cfa29

File tree

1 file changed

+43
-0
lines changed
  • Programmers - 문제풀이/타겟 넘버

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
풀이 시작 : 2023.08.09 13:03
3+
4+
- 순서를 바꾸지 않아도 된다 -> 덧셈 뺄셈 연산자만 바꿔가며 경우의 수를 판단
5+
- 그리디한 접근은 어려울 것 같고(어차피 다 탐색해야함), 주어지는 수의 개수가 많지 않아서(20개) 완전탐색(dfs)으로 구현할 수 있을듯 함
6+
- 모든 수를 순서대로 탐색해야하므로 가지 치기는 없고, 그냥 부호만 바꿔가며 가지를 뻗어나가기만 하면 될 것 같다.
7+
8+
풀이 완료 : 2023.08.09 13:22
9+
'''
10+
11+
from typing import List
12+
13+
14+
result = 0
15+
16+
def dfs(idx: int, numbers: List[int], target: int, total: int):
17+
global result
18+
19+
if idx == len(numbers): # 모든 수의 탐색이 끝난 경우
20+
result += 1 if total == target else 0 # 해당 경우의 수의 결과가 target number이면 최종 결과에 +1
21+
return # 이는 재귀의 종료 조건임
22+
23+
dfs(idx+1, numbers, target, total+numbers[idx]) # idx번째를 더하고 idx+1번째 탐색 시작
24+
dfs(idx+1, numbers, target, total-numbers[idx]) # idx번째를 빼고 idx+1번째 탐색 시작
25+
26+
27+
def solution(numbers: List[int], target: int) -> int:
28+
global result
29+
30+
dfs(0, numbers, target, 0) # 0번 인덱스부터 탐색 시작
31+
32+
return result
33+
34+
def main() -> None:
35+
global result
36+
case1 = [[1, 1, 1, 1, 1], 3] # 5
37+
case2 = [[4, 1, 2, 1], 2] # 2
38+
39+
print(solution(*case1)) # 5
40+
result = 0 # 전역변수 초기화
41+
print(solution(*case2)) # 2
42+
43+
main()

0 commit comments

Comments
 (0)