<p>We call a positive integer <strong>special</strong> if all of its digits are <strong>distinct</strong>.</p>

<p>Given a <strong>positive</strong> integer <code>n</code>, return <em>the number of special integers that belong to the interval </em><code>[1, n]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> All the integers from 1 to 5 are special.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> n = 135
<strong>Output:</strong> 110
<strong>Explanation:</strong> There are 110 integers from 1 to 135 that are special.
Some of the integers that are not special are: 22, 114, and 131.</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>9</sup></code></li>
</ul>

class Solution:
    def countSpecialNumbers(self, n: int) -> int:
        # res, temp = 0, 1
        # digits = int(log10(n))
        # for i in range(1, digits + 1):
        #     res += 9 * temp
        #     temp *= 10 - i
        # memo = [1]
        # for i in range(2, 10):
        #     memo.append(memo[-1] * i)
        # used = set()
        # for i in range(digits + 1):
        #     start = 0
        #     if i == 0:
        #         start = 1
        #     div, n = divmod(n, 10 ** (digits - i))
        #     for j in range(start, div + (i == digits)):
        #         if j not in used:
        #             shift = digits - i
        #             res += memo[max(8 - i, 0)] // memo[max(8 - i - shift, 0)]
        #     if div in used:
        #         break
        #     used.add(div)
        # return res

        s = str(n)

        @cache
        def dfs(i, mask, is_limit, is_num):
            if i == len(s):
                return int(is_num)
            res = 0
            if not is_num:
                res += dfs(i + 1, mask, False, False)
                lo = 1
            else:
                lo = 0
            up = int(s[i]) if is_limit else 9
            for d in range(lo, up + 1):
                if mask >> d & 1 == 0:
                    res += dfs(i + 1, mask | (1 << d), is_limit and d == up, True)
            return res

        return dfs(0, 0, True, False)
223