μ•Œκ³ λ¦¬μ¦˜ πŸ’‘/ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€

깊이/λ„ˆλΉ„ μš°μ„  탐색(DFS/BFS)_νƒ€κ²Ÿ λ„˜λ²„.py(파이썬)

@ENFJ 2024. 10. 1. 17:11

DFS λ₯Ό μ‚¬μš©ν•˜λ©΄ λͺ¨λ“  경우의 수λ₯Ό νƒμƒ‰ν•˜λ©°, 각 숫자λ₯Ό λ”ν•˜κ±°λ‚˜ λΉΌλŠ” 두 κ°€μ§€ 선택을 μž¬κ·€μ μœΌλ‘œ μˆ˜ν–‰ν•©λ‹ˆλ‹€.

 

풀이 κ³Όμ •:

1. 각 숫자λ₯Ό 순차적으둜 μ„ νƒν•˜μ—¬, λ”ν•˜λŠ” κ²½μš°μ™€ λΉΌλŠ” 경우λ₯Ό λͺ¨λ‘ νƒμƒ‰ν•œλ‹€.

2. λͺ¨λ“  μˆ«μžμ— λŒ€ν•΄ 연산을 λ§ˆμ³€μ„ λ•Œ, 결과값이 νƒ€κ²Ÿ λ„˜λ²„μ™€ κ°™μœΌλ©΄ λ°©λ²•μ˜ 수λ₯Ό 1 증가 μ‹œν‚΅λ‹ˆλ‹€.

3. μ΅œμ’…μ μœΌλ‘œ λͺ¨λ“  경우의 수λ₯Ό νƒμƒ‰ν•œ ν›„, λ°©λ²•μ˜ 수λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

 

def solution(numbers, target):
    answer = 0 # 타켓 λ„˜λ²„λ₯Ό λ§Œλ“€ 수 μžˆλŠ” λ°©λ²•μ˜ 수λ₯Ό μ €μž₯ν•˜λŠ” λ³€μˆ˜

# dfs ν•¨μˆ˜λŠ” ν˜„μž¬ 숫자의 인덱슀(index)와 ν˜„μž¬κΉŒμ§€μ˜ ν•©(current_sum)을 λ°›μ•„ μž¬κ·€μ μœΌλ‘œ ν˜ΈμΆœλ©λ‹ˆλ‹€.
    def dfs(index, current_sum):
        # nonlocal answer 은 λ‚΄λΆ€ν•¨μˆ˜μΈ dfsμ—μ„œ λ°”κΉ₯ ν•¨μˆ˜μ˜ λ³€μˆ˜ answerλ₯Ό μˆ˜μ •ν•  수 있게 ν•΄μ€Œ.
        # 이게 μ—†μœΌλ©΄ answerλŠ” ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ 둜컬 λ³€μˆ˜λ‘œ μΈμ‹λ©λ‹ˆλ‹€.
        nonlocal answer  

        # λͺ¨λ“  숫자λ₯Ό μ²˜λ¦¬ν•œ 경우

        #**if index == len(numbers):**λŠ” ν˜„μž¬ indexκ°€ numbers λ°°μ—΄μ˜ 끝에 λ„λ‹¬ν–ˆλŠ”μ§€ ν™•μΈν•©λ‹ˆλ‹€. 
        # λ°°μ—΄μ˜ λͺ¨λ“  숫자λ₯Ό λ‹€ μ²˜λ¦¬ν–ˆλ‹€λŠ” μ˜λ―Έμž…λ‹ˆλ‹€.
        if index == len(numbers): 
            if current_sum == target:
                answer += 1

            # κ·Έ ν›„μ—λŠ” **return**으둜 ν•¨μˆ˜κ°€ μ’…λ£Œλ©λ‹ˆλ‹€. 더 이상 계산할 μˆ«μžκ°€ μ—†κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€.
            return
        

        # ν˜„μž¬ 숫자λ₯Ό λ”ν•˜λŠ” 경우
        dfs(index + 1, current_sum + numbers[index])

        # ν˜„μž¬ 숫자λ₯Ό λΉΌλŠ” 경우
        dfs(index +1,current_sum - numbers[index])
    
    # 탐색 μ‹œμž‘
    #초기 호좜: 첫 번째 μˆ«μžλΆ€ν„° 탐색을 μ‹œμž‘ν•΄μ•Ό ν•˜λ―€λ‘œ dfs(0, 0)을 ν˜ΈμΆœν•©λ‹ˆλ‹€. μ—¬κΈ°μ„œ 0은 처음 인덱슀이고, 두 번째 0은 ν˜„μž¬ ν•©κ³„μž…λ‹ˆλ‹€. 
    # 즉, 아무 μˆ«μžλ„ 아직 λ”ν•˜κ±°λ‚˜ λΉΌμ§€ μ•Šμ€ μƒνƒœμ—μ„œ μ‹œμž‘ν•©λ‹ˆλ‹€.
    dfs(0, 0)


    #λͺ¨λ“  탐색이 μ™„λ£Œλ˜λ©΄, answer κ°’(νƒ€κ²Ÿ λ„˜λ²„λ₯Ό λ§Œλ“œλŠ” λ°©λ²•μ˜ 수)을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
    return answer


numbers = [1, 1, 1, 1, 1]
target = 3

result = solution(numbers, target)
print(result) # 좜λ ₯: 5