Given an array of digits which is sorted in non-decreasing order. 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.
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.
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.
Input: digits = ["7"], n = 8
Output: 1
1 <= digits.length <= 9digits[i].length == 1digits[i] is a digit from '1' to '9'.digits are unique.digits is sorted in non-decreasing order.1 <= n <= 109The brute force method involves generating all possible numbers from the given digit set and checking if they are less than or equal to the target number N. This approach is based on generating permutations of increasing lengths and counting how many are valid.
N to a string to easily access individual digits.N using the digits.N and count it.O((D.length)^(log10 N)) where log10 N is the number of digits in N.O(log10 N) for the recursive stack.This approach leverages digit dynamic programming to count the valid numbers directly instead of generating and validating them one by one. We pre-compute the numbers using dynamic programming, breaking the problem into manageable sub-problems.
O(nLen * D.length) where nLen is the number of digits in N.O(nLen * D.length) for memoization table.Instead of generating numbers one-by-one, this approach leverages counting principles. We break down the problem by counting numbers having fewer digits than N and exactly digits of N.
N.N.O(nLen * D.length) where nLen is the number of digits in N.O(1) no extra space required beyond variables.