๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Level 2 - ํƒ€๊ฒŸ ๋„˜๋ฒ„

by HandHand 2021. 3. 1.

๋ฌธ์ œ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํƒ€๊ฒŸ ๋„˜๋ฒ„

ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ์ˆ˜์— ๋ง์…ˆ๊ณผ ๋บ„์…ˆ์„ ํ™œ์šฉํ•ด์„œ ๋ชฉํ‘œ ์ˆซ์ž๋ฅผ ๋งŒ๋“œ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ตœ๋Œ€ 20๊ฐœ์˜ ์ˆซ์ž๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  2๊ฐ€์ง€ ์—ฐ์‚ฐ๋ฐ–์— ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ์ตœ๋Œ€ 2^20 ๊ฐœ์˜ ์ƒํƒœ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

์ด๋Š” ๋Œ€๋žต 1000000 ์œผ๋กœ ์ถฉ๋ถ„ํžˆ ์‹œ๊ฐ„ ๋‚ด์— ์ˆ˜ํ–‰์ด ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ DFS ๋ฅผ ํ™œ์šฉํ•ด ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ๊ฐ€๋Šฅํ•œ ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ ์„ธ์–ด์คฌ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


def dfs(numbers, depth, here, target):
    if depth == len(numbers):
        return 1 if here == target else 0

    ret = 0
    for operand in [-numbers[depth], numbers[depth]]:
        ret += dfs(numbers, depth+1, here + operand, target)

    return ret


def solution(numbers, target):
    start = 0
    ans = dfs(numbers, 0, start, target)
    return ans
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€