재귀 호출을 메모할 때 엄청난 효율성 차이 (Drastic efficiency difference when memoizing recursive calls)


문제 설명

재귀 호출을 메모할 때 엄청난 효율성 차이 (Drastic efficiency difference when memoizing recursive calls)

이 LeetCode 문제를 수행하는 동안 내가 코딩하기로 결정한 버전에 따라 성능에 큰 차이가 있습니다(주석된 부분 참조). 그 중 하나는 더 간결하지만 차이가 있어야 할 이유가 없습니다. 설명을 해주시면 감사하겠습니다.

class Solution:

    def rec_memo(self, nums, index, curr_sum, target, memo):

        if curr_sum == target:
            return True
        elif curr_sum > target or index == len(nums):
            return False

        if (index, curr_sum) in memo:
            return memo[(index, curr_sum)]

# This line (below) is significantly more efficient   

#         memo[(index, curr_sum)] = self.rec_memo(nums, index + 1, curr_sum + nums[index], target, memo) or self.rec_memo(nums, index + 1, curr_sum, target, memo)

# These lines (below) are significantly less efficient

#         choose_num = self.rec_memo(nums, index + 1, curr_sum + nums[index], target, memo)
#         not_choose_num = self.rec_memo(nums, index + 1, curr_sum, target, memo)

#         memo[(index, curr_sum)] = choose_num or not_choose_num

        return memo[(index, curr_sum)]


    def canPartition(self, nums: List[int]) ‑> bool:

        sum = 0
        for i in range(0, len(nums), 1):
            sum += nums[i]

        if sum % 2 != 0:
            return False

        memo = {}
        return self.rec_memo(nums, 0, 0, sum // 2, memo)


참조 솔루션

방법 1:

The first one:

self.rec_memo(nums, index + 1, curr_sum + nums[index], target, memo) or \
self.rec_memo(nums, index + 1, curr_sum, target, memo)

won't evaluate the latter call to self.rec_memo() if the first one returns True, due to short‑circuit evaluation.

However, with the second one:

choose_num = self.rec_memo(nums, index + 1, curr_sum + nums[index], target, memo)
not_choose_num = self.rec_memo(nums, index + 1, curr_sum, target, memo)
memo[(index, curr_sum)] = choose_num or not_choose_num

you'll always make the second recursive call, no matter the result of the first call to rec_memo(). The slowdown you're observing is likely the result of these additional recursive calls.

(by csguyBrokenBenchmark)

참조 문서

  1. Drastic efficiency difference when memoizing recursive calls (CC BY‑SA 2.5/3.0/4.0)

#dynamic-programming #Python #recursion #memoization






관련 질문

나머지 숫자의 xor가 0인 부분 집합의 수를 찾습니다. (Find number of subsets, that xor of remaining numbers equals to 0)

재귀 대신 동적 프로그래밍을 사용하여 가장 큰 공통 접미사(자바스크립트) 찾기 (Use dynamic programming instead of recursion to find largest common suffix (javascript))

제거 방법 : java.lang.OutOfMemoryError (how to remove : java.lang.OutOfMemoryError)

가장 효율적인 좌석 배치 (Most efficient seating arrangement)

aglorithm의 복잡성을 가진 춤 (A dance with an aglorithm's complexity)

장애물이 있는 처음부터 끝까지 경로의 수를 계산합니다. (Count the number of paths from start to end with obstacles)

직사각형 필드 내에서 다양한 크기의 직사각형을 효율적으로 배치 (Efficient placement of variable size rectangles within a rectangular field)

기차 또는 버스를 이용할 수 있는 도시 간 최단 경로 DYNAMIC PROGRAMMING (Shortest path between cities that you can use either train or bus DYNAMIC PROGRAMMING)

인덱스가 오름차순으로 정렬되도록 주어진 합계를 갖는 하위 배열의 개수 (Count of sub-arrays with a given sum such that the indices are in ascending order)

2차원 배열의 경로 수 계산(그리드 Traveller) (Count number of paths on 2d-array (grid Traveller))

n개의 볼과 m개의 빈이 주어지고 각 빈이 특정 용량을 가질 때, 몇 개의 조합이 있습니까? (Given n balls and m bins, each bin with a certain capacity, how many combinations are there?)

재귀 호출을 메모할 때 엄청난 효율성 차이 (Drastic efficiency difference when memoizing recursive calls)







코멘트