Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

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

meeeeejin 2021. 3. 15. 21:34

๋ฌธ์ œ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/43165

 

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

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

programmers.co.kr

 

๋ฌธ์ œ ์„ค๋ช…

๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ DFS(๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰)์œผ๋กœ ํ™•์ธํ•ด์„œ ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒฝ์šฐ๋ฅผ ์…Œ์Šต๋‹ˆ๋‹ค. 

 

 

 

์†Œ์Šค์ฝ”๋“œ

answer = 0

def dfs(idx, numbers, total_sum, target):
    global answer
    n = len(numbers)
    # ๋งˆ์ง€๋ง‰ ์›์†Œ๊นŒ์ง€ ๊ณ„์‚ฐํ–ˆ๋‹ค๋ฉด return
    if idx == n - 1:
        # ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒฝ์šฐ
        if total_sum == target:
            answer += 1
        return
    # ๋‹ค์Œ ์›์†Œ๋ฅผ ๋”ํ•  ๊ฒฝ์šฐ
    dfs(idx + 1, numbers, total_sum + numbers[idx + 1], target)
    # ๋‹ค์Œ ์›์†Œ๋ฅผ ๋บ„ ๊ฒฝ์šฐ
    dfs(idx + 1, numbers, total_sum - numbers[idx + 1], target)

def solution(numbers, target):
    global answer
    dfs(-1, numbers, 0, target)
    return answer

 

 

 

 

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

โœ” ์žฌ๊ท€๋ฅผ ์ด์šฉํ•œ ํ’€์ด

์˜ˆ๋ฅผ ๋“ค์–ด numbers = [1, 2, 3, 4, 5], target = 6 ์ผ ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐํ•ด๋ด…์‹œ๋‹ค. 

๋งŒ์•ฝ [2, 3, 4, 5]๋กœ 5 ๋˜๋Š” 7์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค๋ฉด, 1์„ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ ํƒ€๊ฒŸ ๋„˜๋ฒ„์ธ 6์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

์ด์™€ ๊ฐ™์€ ์•„์ด๋””์–ด๋กœ ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ํ’€์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. 

def solution(numbers, target):
    # numbers๋กœ target์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ
    if not numbers and target == 0 :
        return 1
    # numbers๋กœ target์„ ๋งŒ๋“ค ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ
    elif not numbers:
        return 0
    else:
        # ๋ฆฌ์ŠคํŠธ์˜ ์•ž ์›์†Œ๋ถ€ํ„ฐ ์ˆœ์„œ๋Œ€๋กœ
        # (ํ•ด๋‹น ์›์†Œ๋ฅผ ๋”ํ–ˆ์„ ๋•Œ์˜ ์ •๋‹ต ๊ฐœ์ˆ˜) + (ํ•ด๋‹น ์›์†Œ๋ฅผ ๋บ์„ ๋•Œ์˜ ์ •๋‹ต ๊ฐœ์ˆ˜)
        return solution(numbers[1:], target-numbers[0]) + solution(numbers[1:], target+numbers[0])

 

 

โœ” product๋ฅผ ์ด์šฉํ•œ ์™„์ „ ํƒ์ƒ‰ ํ’€์ด

from itertools import product

def solution(numbers, target):
    _list = [(x, -x) for x in numbers]
    s = list(map(sum, product(*_list)))
    return s.count(target)

 

728x90