ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ํ˜„์žฌ ๊ฐ’์„ ๋”ํ•˜๋Š๋ƒ, ๋นผ๋ƒ์— ๋”ฐ๋ผ 2 ๊ฐ€์ง€๋กœ ๋‚˜๋‰˜๊ฒŒ ๋œ๋‹ค. ์ด๋Š” DFS๋ฅผ ํ†ตํ•ด ํƒ์ƒ‰ํ•  ๊ฒฝ์šฐ ๊ฐ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ํŒ๋‹จํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ฐ ๋…ธ๋“œ ๋งˆ๋‹ค 2๊ฐœ์˜ ๊ฐ€์ง€๋กœ ๋ปฃ์–ด๋‚˜๊ฐ€๊ฒŒ ๋˜๋ฏ€๋กœ, ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ depth(์ˆซ์ž์˜ ์ˆ˜) ๋งŒํผ ๋„๋‹ฌ ํ•˜์˜€์„ ๋•Œ, ๊ณ„์‚ฐ ๋œ ๊ฐ’๊ณผ target๊ณผ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

def dfs(numbers, target, i = 0):
    answer = 0
    if i == len(numbers):
        if sum(numbers) == target:
            return 1
        return 0
    
    answer += dfs(numbers, target, i + 1)
    numbers[i] *= -1
    answer += dfs(numbers, target, i + 1)
    
    return answer


def solution(numbers, target):
    return dfs(numbers, target)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€