Numbers At Most N Given Digit Set LeetCode solution in Python
1class Solution:2def atMostNGivenDigitSet(self, digits, n):3cache = {}4target = str(n)56def helper(idx, isBoundary, isZero):7if idx == len(target):8return 19if (idx, isBoundary, isZero) in cache:10return cache[(idx, isBoundary, isZero)]1112res = 013if isZero and idx != len(target) - 1:14res += helper(idx + 1, False, True)15for digit in digits:16if isBoundary and int(digit) > int(target[idx]):17continue18res += helper(19idx + 1,20True if isBoundary and digit == target[idx] else False,21False,22)2324cache[(idx, isBoundary, isZero)] = res25return res2627return helper(0, True, True)