Given an array of digits, you can write numbers using each digits[i] as many times as we want.  For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
Return the number of positive integers that can be generated that are less than or equal to a given integer n.
 
Example 1:
Input: digits = ["1","3","5","7"], n = 100
Output: 20
Explanation: 
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.

Example 2:
Input: digits = ["1","4","9"], n = 1000000000
Output: 29523
Explanation: 
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits array.

Example 3:
Input: digits = ["7"], n = 8
Output: 1

 
Constraints:

1 <= digits.length <= 9
digits[i].length == 1
digits[i] is a digit from '1' to '9'.
All the values in digits are unique.
1 <= n <= 109

Difficulty: MEDIUM_HARD
Starter code: class Solution:
    def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
        

Solutions:
class Solution:

	def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
		count = 0
		length = 1
		n_str = str(n)
		while length < len(n_str):
			count += len(digits) ** length
			length += 1
		digits_sorted = sorted(digits)
		current_digit = 0
		while current_digit < length:
			for digit in digits_sorted:
				next_round = False
				if digit < n_str[current_digit]:
					count += len(digits) ** (length - current_digit - 1)
				elif digit > n_str[current_digit]:
					return count
				elif current_digit == length - 1:
					return count + 1
				else:
					current_digit += 1
					next_round = True
					break
			if not next_round:
				return count
		return count


class Solution:

	def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
		ns = str(n)
		dp = 1
		digits.sort()
		(M, N) = (len(ns), len(digits))
		for i in range(M - 1, -1, -1):
			dp2 = 0
			for d in digits:
				if d > ns[i]:
					break
				if d < ns[i]:
					dp2 += N ** (M - 1 - i)
				else:
					dp2 += dp
			dp = dp2
		return dp + sum((N ** i for i in range(1, M)))


class Solution:

	def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:

		def less(digits, d):
			return len([i for i in digits if i < d])
		cnt = 0
		(ld, ln) = (len(digits), len(str(n)))
		N = str(n)
		for i in range(ln - 1):
			cnt += ld ** (i + 1)
		for i in range(ln):
			cnt += less(digits, N[i]) * ld ** (ln - i - 1)
			if N[i] not in digits:
				return cnt
		return cnt + 1