Leetcode 964.Least Operators to Express Number

Well, we can also solve in dp format.
Python3

    @functools.lru_cache(None)
    def leastOpsExpressTarget(self, x, y):
        k = int(math.log(y, x)) + 1
        def dfs(y, k):
            if k == 0 or y == 0:
                return y + y - 1
            need, left = divmod(y, x**k)
            return min(dfs(left, k - 1) + need * k, dfs(x**k - left, k - 1) + (need + 1) * k)
        return dfs(y, k)

你可能感兴趣的:(Leetcode 964.Least Operators to Express Number)