<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:
        # Convert the number to a string for easier digit manipulation
        s = str(n)
        len_s = len(s)
        
        # dp[i][mask] represents the number of special numbers of length i
        # with digits represented by the bitmask mask
        dp = [[-1] * (1 << 10) for _ in range(len_s + 1)]
        
        def dfs(pos, mask, limit):
            if pos == len_s:
                return 1 if mask != 0 else 0
            
            if not limit and dp[pos][mask] != -1:
                return dp[pos][mask]
            
            res = 0
            up = int(s[pos]) if limit else 9
            
            for digit in range(up + 1):
                if mask & (1 << digit):
                    continue
                
                next_mask = mask if digit == 0 and mask == 0 else mask | (1 << digit)
                
                if limit and digit == up:
                    res += dfs(pos + 1, next_mask, True)
                else:
                    res += dfs(pos + 1, next_mask, False)
            
            if not limit:
                dp[pos][mask] = res
            
            return res
        
        return dfs(0, 0, True)

# Example usage:
solution = Solution()
print(solution.countSpecialNumbers(20))  # Output: 19
print(solution.countSpecialNumbers(5))   # Output: 5
print(solution.countSpecialNumbers(135)) # Output: 110
188