๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํƒ€์ผ“ ๋„˜๋ฒ„ - python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํƒ€์ผ“ ๋„˜๋ฒ„ - python

BAY 2023. 8. 2. 10:40
728x90

๋ฌธ์ œ ์ •๋ณด

๋ฌธ์ œ ์œ ํ˜• ๋‚œ์ด๋„ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„ ํ•ด๊ฒฐ ์œ ๋ฌด ์Šค์Šค๋กœ ๊ตฌํ˜„ ์„ฑ๊ณต
DFS/BFS level2 33m O O

 

์„ค๊ณ„ ๋ฐฉ๋ฒ•

  • numbers ๋Œ๋ฉด์„œ arr ๋ชจ๋“  ์š”์†Œ์— ๋Œ€ํ•ด -num๊ณผ +num์„ ํ•ด์คŒ
  • arr ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋Œ ๋•Œ๋Š” arr.popleft()๋กœ ํ•˜๋‚˜์”ฉ ๋นผ์„œ ์‚ฌ์šฉ
  • -num๊ณผ +num์„ ํ•ด์ค€ ์š”์†Œ๋Š” arr.append()
  • numbers ๋‹ค ๋Œ์•˜์œผ๋ฉด ๋งˆ์ง€๋ง‰ arr์— ์žˆ๋Š” ์š”์†Œ ์ค‘ target๊ณผ ์ผ์น˜ํ•˜๋Š” ์š”์†Œ ์นด์šดํŒ…

์ฝ”๋“œ

๋‚ด ํ’€์ด

from collections import deque

def solution(numbers, target):
    arr = deque([0])
    for num in numbers:
        for _ in range(len(arr)):
            v = arr.popleft()
            arr.append(v - num)
            arr.append(v + num)
    return arr.count(target)

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด 1

answer = 0
def DFS(idx, numbers, target, value):
    global answer
    N = len(numbers)
    if(idx== N and target == value):
        answer += 1
        return
    if(idx == N):
        return

    DFS(idx+1,numbers,target,value+numbers[idx])
    DFS(idx+1,numbers,target,value-numbers[idx])
def solution(numbers, target):
    global answer
    DFS(0,numbers,target,0)
    return answer

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด 2

from itertools import product
def solution(numbers, target):
    l = [(x, -x) for x in numbers]
    s = list(map(sum, product(*l)))
    return s.count(target)
728x90