<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:
        n = str(n)
        def count(i: int, m: int) -> int:
            return 1 if i == 0 else (m - i + 1) * count(i - 1, m)
        def dfs(i: int, mask: int) -> int:
            if i >= len(n):
                return 1;
            cur = ord(n[i]) - ord('0');
            res = dfs(i + 1, mask + (1 << cur)) if not mask & (1 << cur) else 0
            for j in range(0 if i > 0 else 1, cur):
                res += count(len(n) - i - 1, 9 - i) if not mask & (1 << j) else 0
            return res
        return dfs(0, 0) + sum(9 * count(i - 1, 9) for i in range(1, len(n)))
36