๋ฐ์ํ
๋ฌธ์
ํ์ด
BFS ๋ฅผ ์ด์ฉํ์ฌ ํ ์ ์๋ค. ๋ค์ ์๋ฅผ ๋ํ๊ณ ๋นผ๋ ๊ฒฝ์ฐ ๋๊ฐ์ง๋ฅผ ๋ชจ๋ ํ์ ๋ฃ์ผ๋ฉด์ BFS๋ฅผ ์งํ์ํค๊ณ target ๊ณผ ๋์ผํ ๊ฒฝ์ฐ์ ์นด์ดํธํด์ค๋ค.
์ฝ๋
from collections import deque
def solution(numbers, target):
answer = 0
queue = deque()
n = len(numbers)
queue.append([numbers[0],0])
queue.append([-1*numbers[0],0])
while queue:
temp, idx = queue.popleft()
idx += 1
if idx < n:
queue.append([temp+numbers[idx], idx])
queue.append([temp-numbers[idx], idx])
else:
if temp == target:
answer += 1
return answer
๋ฐ์ํ
'๐ป Programming > ์๊ณ ๋ฆฌ์ฆ ํ ์คํธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[python] ํ๋ก๊ทธ๋๋จธ์ค_์๋ฌผ์ ์ ์ด์ (์์ ํ์) (0) | 2022.02.14 |
---|---|
[python] ํ๋ก๊ทธ๋๋จธ์ค_์นดํซ (์์ ํ์) (0) | 2022.02.14 |
[python] ํ๋ก๊ทธ๋๋จธ์ค_๋จ์ด๋ณํ (DFS&BFS) (0) | 2022.02.06 |
[python] ํ๋ก๊ทธ๋๋จธ์ค_๋คํธ์ํฌ (DFS&BFS) (0) | 2022.02.06 |
[python] ๋ฐฑ์ค18405_๊ฒฝ์์ ์ ์ผ (DFS&BFS) (0) | 2022.02.06 |