ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv2] ํƒ€๊ฒŸ๋„˜๋ฒ„ ํŒŒ์ด์ฌ

2021. 4. 5. 23:14ใ†๐Ÿ”ฑ Algorithm/Else

 

 

 

ํฌ์ธํŠธ

  1. ๋ฆฌ์ŠคํŠธ ๋‚ด ์›์†Œ๋Š” ๋ชจ๋‘ ๊ฐ™๋‹ค.
  2. ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งž์ถ”๋Š” ๋ฐฉ๋ฒ•์ด ** ๋ช‡๊ฐ€์ง€** ์ธ์ง€๋งŒ ์•Œ๋ฉด ๋œ๋‹ค.

์ „ํ˜•์ ์ธ ์žฌ๊ท€ ๋ฌธ์ œ๋กœ, dfs๋ฅผ ์ด์šฉํ•˜์—ฌ ํ’€ ์ˆ˜๋„ ์žˆ์ง€๋งŒ, itertools๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ product๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ pythonicํ•œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

ํ’€์ด 1) product, ๊ณฑ์ง‘ํ•ฉ


from itertools import product

def solution(numbers, target):
    temp = [(i, -i) for i in numbers]
    result = [1 for i in product(*temp) if sum(i) == target]
    return len(result)

 

temp ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด

temp = [(i, -i) for i in numbers]
print(temp)

>>> [(1, -1), (1, -1), (1, -1), (1, -1), (1, -1)]

 

product๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ temp ์›์†Œ๋“ค์˜ ๊ณฑ์ง‘ํ•ฉ์„ ์ถœ๋ ฅํ•˜๋ฉด ์ „์ฒด ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.

for i in product(*temp):
    print(i)

>>> (1, 1, 1, 1, 1)
(1, 1, 1, 1, -1)
(1, 1, 1, -1, 1)
(1, 1, 1, -1, -1)
(1, 1, -1, 1, 1)
(1, 1, -1, 1, -1)
...

=> ์ด 32๊ฐ€์ง€ 

์ด 32๊ฐ€์ง€ ๊ฒฝ์šฐ์˜ ์ง‘ํ•ฉ ์ค‘, ์ง‘ํ•ฉ์˜ ์ดํ•ฉ์ด target๊ณผ ๊ฐ™์€ ์ง‘ํ•ฉ์˜ ๊ฐฏ์ˆ˜๋ฅผ ๊ณ ๋ฅด๋ฉด ๋œ๋‹ค. (์–ด๋–ค ์ง‘ํ•ฉ์ด ํƒ€๊ฒŸ์„ ๋งž์ถ”๋Š”์ง€๋Š” ์ƒ๊ด€์—†๋‹ค)

๋ฆฌ์ŠคํŠธ ์ปดํ”„๋ฆฌํ—จ์…˜์œผ๋กœ ์กฐ๊ฑด์˜ ๋งž๋Š” ๊ฒฝ์šฐ 1์„ ๋ฆฌํ„ดํ•˜์—ฌ result ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•˜๊ณ , result ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ๋‹ต์œผ๋กœ ์ถœ๋ ฅ.

 

ํ’€์ด 2) DFS, ์žฌ๊ท€

 

result = 0

def solution(numbers, target):
    global result

    dfs(0, numbers, target, 0)
    return result

def dfs(idx, numbers, target, curr):
    N = len(numbers)
    global result
    if idx == N and curr == target:
        result += 1
        return
    if idx == N:
        return

    dfs(idx + 1, numbers, target, curr + numbers[idx])
    dfs(idx + 1, numbers, target, curr - numbers[idx])

 

๊ถ๊ธˆ์ 

  • DFS ํ’€์ด์—์„œ, numbers[idx] ๋ถ€๋ถ„์— idx ๋Œ€์‹  0์„ ๋„ฃ์œผ๋‹ˆ ์—๋Ÿฌ๊ฐ€ ๋‚ฌ๋‹ค.
  • ๋ชจ๋“  ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๊ฐ€ ๊ฐ™์œผ๋‹ˆ ๋‹น์—ฐํžˆ idx ๋Œ€์‹  0์„ ๋„ฃ์–ด๋„ ์ƒ๊ด€์—†๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, idx๋ฅผ ๋„ฃ์œผ๋‹ˆ ํ†ต๊ณผ, 0์„ ๋„ฃ์œผ๋‹ˆ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
  • ์ด์œ ๋ฅผ ์•„์‹œ๋Š” ๋ถ„์€ ๋Œ“๊ธ€ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค :) ใ