์ƒˆ์†Œ์‹

๐Ÿงฎ PS

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

  • -

https://programmers.co.kr/learn/courses/30/lessons/43165

 

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

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

programmers.co.kr

 

๋ฌธ์ œ ์œ ํ˜• : DFS / BFS

 

ํ’€์ด 

dfs(idx, ๋ˆ„์ ๊ฐ’):
	if idx == numbers์˜ ๊ฐœ์ˆ˜  # ์žฌ๊ท€ ์ข…๋ฃŒ์กฐ๊ฑด : ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋บ๋‹ค๋ฉด ์ข…๋ฃŒ
		if ๋ˆ„์ ๊ฐ’ == target:   # ๋ชจ๋“ ์š”์†Œ๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋บ๋Š”๋ฐ, ๋ˆ„์ ๊ฐ’์ด target๊ณผ ์ผ์น˜ํ•˜๋ฉด answer += 1
			answer += 1
		return

	# ์•„์ง ์ข…๋ฃŒ์ „์ด๋ผ๋ฉด
	dfs(idx, ๋ˆ„์ ๊ฐ’ + numbers[idx]) # ๋‹ค์Œ ์ˆซ์ž๋ฅผ ๋”ํ•˜๋Š” ๊ฒฝ๋กœ
	dfs(idx, ๋ˆ„์ ๊ฐ’ - numbers[idx])  # ๋‹ค์Œ ์ˆซ์ž๋ฅผ ๋นผ๋Š” ๊ฒฝ๋กœ

 

answer = 0

def dfs(max_len, cnt, result, target, numbers):
    
    if cnt == max_len:
        if result == target:
            global answer
            answer += 1
        return
    dfs(max_len, cnt + 1, result + numbers[cnt] ,target, numbers)
    dfs(max_len, cnt + 1, result - numbers[cnt] ,target, numbers)    
    


def solution(numbers, target):
    global answer
    max_len = len(numbers)
    dfs(max_len, 0, 0, target, numbers)
    return answer

 

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.