|
21 | 21 |
|
22 | 22 | ## Solutions
|
23 | 23 |
|
24 |
| -### Solution 1 |
| 24 | +### Solution 1: Digit DP |
| 25 | + |
| 26 | +This problem is essentially about finding the number of occurrences of the digit $2$ in the given interval $[l,..r]$. The count is related to the number of digits and the digit at each position. We can use the idea of Digit DP to solve this problem. In Digit DP, the size of the number has little impact on the complexity. |
| 27 | + |
| 28 | +For the interval $[l,..r]$, we usually transform it into $[1,..r]$ and then subtract $[1,..l - 1]$, i.e., |
| 29 | + |
| 30 | +$$ |
| 31 | +ans = \sum_{i=1}^{r} ans_i - \sum_{i=1}^{l-1} ans_i |
| 32 | +$$ |
| 33 | + |
| 34 | +However, for this problem, we only need to find the value in the interval $[1,..r]$. |
| 35 | + |
| 36 | +Here, we use memoization to implement Digit DP. We start from the top and search down to the bottom to get the number of schemes, then return the answer layer by layer and accumulate it, finally getting the final answer from the starting point of the search. |
| 37 | + |
| 38 | +The basic steps are as follows: |
| 39 | + |
| 40 | +1. Convert the number $n$ into an int array $a$, where $a[1]$ is the least significant digit, and $a[len]$ is the most significant digit. |
| 41 | +2. Design the function $dfs()$ based on the problem information. For this problem, we define $dfs(pos, cnt, limit)$, and the answer is $dfs(len, 0, true)$. |
| 42 | + |
| 43 | +Where: |
| 44 | + |
| 45 | +- `pos` represents the number of digits, starting from the least significant digit or the first digit, usually depending on the digit construction property of the problem. For this problem, we choose to start from the most significant digit, so the initial value of `pos` is `len`. |
| 46 | +- `cnt` represents the number of $2$s in the current number. |
| 47 | +- `limit` represents the restriction on the digits that can be filled. If there is no restriction, you can choose $[0,1,..9]$, otherwise, you can only choose $[0,..a[pos]]$. If `limit` is `true` and the maximum value has been reached, then the next `limit` is also `true`. If `limit` is `true` but the maximum value has not been reached, or if `limit` is `false`, then the next `limit` is `false`. |
| 48 | + |
| 49 | +For details on the implementation of the function, please refer to the code below. |
| 50 | + |
| 51 | +The time complexity is $O(\log n)$. |
| 52 | + |
| 53 | +Similar problems: |
| 54 | + |
| 55 | +- [233. Number of Digit One](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md) |
25 | 56 |
|
26 | 57 | <!-- tabs:start -->
|
27 | 58 |
|
|
0 commit comments