DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํƒ€๊ฒŸ ๋„˜๋ฒ„ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํƒ€๊ฒŸ ๋„˜๋ฒ„ (Python)

gimewn 2022. 4. 19. 16:30

link ๐Ÿ”— https://programmers.co.kr/learn/courses/30/lessons/43165

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํƒ€๊ฒŸ ๋„˜๋ฒ„

n๊ฐœ์˜ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜๋“ค์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ •์ˆ˜๋“ค์„ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ์ ์ ˆํžˆ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“ค๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด [1, 1, 1, 1, 1]๋กœ ์ˆซ์ž 3์„ ๋งŒ๋“ค๋ ค๋ฉด ๋‹ค์Œ ๋‹ค์„ฏ ๋ฐฉ๋ฒ•์„ ์“ธ ์ˆ˜

programmers.co.kr

1๏ธโƒฃ ๋”ํ•œ ๊ฒฝ์šฐ์™€ ๋บ€ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ ์„œ DFS ๋Œ๋ฆผ

def solution(numbers, target):
    answer = 0
    def dfs(level, sums):
        global answer
        if level == len(numbers):
            if sums == target:
                answer += 1
            return
        dfs(level+1, sums+numbers[level])
        dfs(level+1, sums-numbers[level])

    dfs(0, 0)
    
    return answer