Python Recursive, use cache function can run faster


  • 0
    C
    from functools import wraps
    class Solution(object):
        def memo(func):
            cache={}
            @wraps(func)
            def wrap(*args):
                if args not in cache:
                    cache[args]=func(*args)
                return cache[args]
            return wrap
        @memo
        def integerReplacement(self, n):
            if n==1:
                return 0
            elif n%2==0:
                return self.integerReplacement(n/2)+1
            else:
                return min(self.integerReplacement(1+n),self.integerReplacement(n-1))+1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.