Algorithms/Programmers

νƒ€κ²Ÿ λ„˜λ²„ (DFS/BFS lv2)

탱저 2021. 8. 6. 13:14

https://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

 

문제 μ„€λͺ…

n개의 음이 μ•„λ‹Œ μ •μˆ˜κ°€ μžˆμŠ΅λ‹ˆλ‹€. 이 수λ₯Ό 적절히 λ”ν•˜κ±°λ‚˜ λΉΌμ„œ νƒ€κ²Ÿ λ„˜λ²„λ₯Ό λ§Œλ“€λ €κ³  ν•©λ‹ˆλ‹€. 예λ₯Ό λ“€μ–΄ [1, 1, 1, 1, 1]둜 숫자 3을 λ§Œλ“€λ €λ©΄ λ‹€μŒ λ‹€μ„― 방법을 μ“Έ 수 μžˆμŠ΅λ‹ˆλ‹€.

 

-1+1+1+1+1 = 3

+1-1+1+1+1 = 3

+1+1-1+1+1 = 3

+1+1+1-1+1 = 3

+1+1+1+1-1 = 3

 

μ‚¬μš©ν•  수 μžˆλŠ” μˆ«μžκ°€ λ‹΄κΈ΄ λ°°μ—΄ numbers, νƒ€κ²Ÿ λ„˜λ²„ target이 λ§€κ°œλ³€μˆ˜λ‘œ μ£Όμ–΄μ§ˆ λ•Œ 숫자λ₯Ό 적절히 λ”ν•˜κ³  λΉΌμ„œ νƒ€κ²Ÿ λ„˜λ²„λ₯Ό λ§Œλ“œλŠ” λ°©λ²•μ˜ 수λ₯Ό return ν•˜λ„λ‘ solution ν•¨μˆ˜λ₯Ό μž‘μ„±ν•΄μ£Όμ„Έμš”.

 

μ œν•œμ‚¬ν•­

  • μ£Όμ–΄μ§€λŠ” 숫자의 κ°œμˆ˜λŠ” 2개 이상 20개 μ΄ν•˜μž…λ‹ˆλ‹€.
  • 각 μˆ«μžλŠ” 1 이상 50 μ΄ν•˜μΈ μžμ—°μˆ˜μž…λ‹ˆλ‹€.
  • νƒ€κ²Ÿ λ„˜λ²„λŠ” 1 이상 1000 μ΄ν•˜μΈ μžμ—°μˆ˜μž…λ‹ˆλ‹€.

μž…μΆœλ ₯ 예

numbers target return

[1, 1, 1, 1, 1] 3 5

[풀이 1] BFS

def solution(numbers, target):
    answer = 0
    current_list = [numbers[0], -numbers[0]]
    print(current_list)
    for i in range(1, len(numbers)):
        next_number = numbers[i]
        print(next_number)
        next_list = []
        for num in current_list:
            next_list.append(num + next_number)
            next_list.append(num - next_number)

        current_list = next_list
        print(current_list)
    for num in current_list:
        if num == target:
            answer += 1
    return answer

print(solution([1, 1, 1, 1, 1], 3))

μˆ˜ν‰μ μœΌλ‘œ 더해 ν•œκΊΌλ²ˆμ— λͺ¨λ“  κ²°κ³Ό μ–»μŒ

 

[풀이 2] DFS

def solution(numbers, target):
    answer = DFS(numbers, target, 0)
    return answer

def DFS(numbers, target, depth):
    answer = 0
    if depth == len(numbers):
        print(numbers)
        if sum(numbers) == target:
            return 1
        else: return 0
    else:
        answer += DFS(numbers, target, depth+1)
        answer += DFS(numbers, target, depth+1)
        numbers[depth] *= -1
        return answer

[풀이 3] 큐 이용

from collections import deque
def solution(numbers, target):
    answer = 0
    queue = deque()
    queue.append([numbers[0],0])  
    queue.append([-numbers[0],0]) # save index
    while queue:
        temp, idx = queue.popleft() 
        idx += 1
        if idx < len(numbers):
            queue.append([temp + numbers[idx], idx])
            queue.append([temp - numbers[idx], idx])
        else:
            if temp == target:
                answer += 1    
    return answer

  • 큐에 μΈλ±μŠ€λž‘ κ°’ 같이 μ €μž₯ν•˜λŠ” 방법 κΈ°μ–΅ν•˜κΈ°!!!!
728x90