DevYoon

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

PS/Programmers

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

gimewn 2022. 4. 16. 21:46

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

 

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

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

programmers.co.kr

 

1๏ธโƒฃ DFS๋ฅผ ํ™œ์šฉ

2๏ธโƒฃ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ target์„ ๋งŒ๋“œ๋Š” ๋ฌธ์ œ์ด๋ฏ€๋กœ, sums ๋ณ€์ˆ˜์— numbers[level]์„ ๋”ํ•ด์ค„ ๋•Œ์™€ ๋นผ์ค„ ๋•Œ๋กœ ๋‚˜๋ˆ„์–ด ๋Œ๋ ค์ฃผ์—ˆ๋‹ค.

 

โœ๏ธ ํ’€์ด

def solution(numbers, target):
    answer = 0
    def dfs(level, sums):
        nonlocal 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

 

โœ๏ธ ๋ฉ”๋ชจ

  • ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฌธ์ œ ํ’€์ด ๋ฐฉ์‹์ด ์•„์ง๋„ ๋‚ฏ์„ค๋‹ค ํ‘ํ‘๐Ÿฅฒ ๋ฌธ์ œ ์—ด์‹ฌํžˆ ํ’€์–ด์„œ ์–ผ๋ฅธ ์ต์ˆ™ํ•ด์ ธ์•ผ์ง€
  • global answer๋กœ ์ฒ˜์Œ์— ํ’€์—ˆ๋”๋‹ˆ ์˜ค๋ฅ˜๊ฐ€ ๋–ด๊ณ , nonlocal๋กœ ๋ฐ”๊ฟ”์ฃผ์—ˆ๋‹ค. ๋งค๋ฒˆ global๋งŒ ์“ฐ๋‹ค๊ฐ€ nonlocal ์“ฐ๋‹ˆ ์ƒˆ๋กญ๋‹ค...โœจ nonlocal ๋ฐฐ์šฐ๊ณ  ์ƒˆ๊นŒ๋งฃ๊ฒŒ ์žŠ์–ด๋ฒ„๋ฆฌ๊ณ  ์žˆ์—ˆ๋‹ค๐Ÿ™ƒ