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μ΄ λ§€κ°λ³μλ‘ μ£Όμ΄μ§ λ μ«μλ₯Ό μ μ ν λνκ³ λΉΌμ νκ² λλ²λ₯Ό λ§λλ λ°©λ²μ μλ₯Ό return νλλ‘ solution ν¨μλ₯Ό μμ±ν΄μ£ΌμΈμ.
μ νμ¬ν
- μ£Όμ΄μ§λ μ«μμ κ°μλ 2κ° μ΄μ 20κ° μ΄νμ λλ€.
- κ° μ«μλ 1 μ΄μ 50 μ΄νμΈ μμ°μμ λλ€.
- νκ² λλ²λ 1 μ΄μ 1000 μ΄νμΈ μμ°μμ λλ€.
μ μΆλ ₯ μ
numbers target return
[1, 1, 1, 1, 1] | 3 | 5 |
[νμ΄ 1] BFS
def solution(numbers, target):
answer = 0
current_list = [numbers[0], -numbers[0]]
print(current_list)
for i in range(1, len(numbers)):
next_number = numbers[i]
print(next_number)
next_list = []
for num in current_list:
next_list.append(num + next_number)
next_list.append(num - next_number)
current_list = next_list
print(current_list)
for num in current_list:
if num == target:
answer += 1
return answer
print(solution([1, 1, 1, 1, 1], 3))
μνμ μΌλ‘ λν΄ νκΊΌλ²μ λͺ¨λ κ²°κ³Ό μ»μ
[νμ΄ 2] DFS
def solution(numbers, target):
answer = DFS(numbers, target, 0)
return answer
def DFS(numbers, target, depth):
answer = 0
if depth == len(numbers):
print(numbers)
if sum(numbers) == target:
return 1
else: return 0
else:
answer += DFS(numbers, target, depth+1)
answer += DFS(numbers, target, depth+1)
numbers[depth] *= -1
return answer
[νμ΄ 3] ν μ΄μ©
from collections import deque
def solution(numbers, target):
answer = 0
queue = deque()
queue.append([numbers[0],0])
queue.append([-numbers[0],0]) # save index
while queue:
temp, idx = queue.popleft()
idx += 1
if idx < len(numbers):
queue.append([temp + numbers[idx], idx])
queue.append([temp - numbers[idx], idx])
else:
if temp == target:
answer += 1
return answer
- νμ μΈλ±μ€λ κ° κ°μ΄ μ μ₯νλ λ°©λ² κΈ°μ΅νκΈ°!!!!
'Algorithms > Programmers' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
νλ‘κ·Έλλ¨Έμ€ μ κ΅μ¬μ¬ (μ΄λΆνμ) (0) | 2021.11.05 |
---|---|
λ€νΈμν¬ DFS/BFS (0) | 2021.08.10 |
μ€ν/ν lv2. κΈ°λ₯ κ°λ° (0) | 2021.07.25 |
μ€ν/ν 1λ² lv2 (0) | 2021.03.05 |
lv1. μ κ· μμ΄λ μΆμ² - μ κ·ννμ (0) | 2021.03.02 |