<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:
        s = str(n)
        # total = []
        # good = set()

        # for i in range(1, n+1):
        #     num_string = str(i)
        #     if len(set(num_string)) != len(num_string):
        #         continue
        #     good.add(num_string)

        @cache
        def dp(s, index, tight, used, leading_zero):
            if index >= len(s):  return 1

            upper_limit = int(s[index]) + 1 if tight else 10
            lower_limit = 1 if (index == len(s) - 1 and leading_zero) else 0

            res = 0
            for i in range(lower_limit, upper_limit):
                if used & (1 << i): continue

                
                
                if i == 0 and leading_zero:
                    new_used = used
                else:
                    new_used = used | 1 << i
                

                new_tight = tight and (i == int(s[index]))
                new_leading_zero = (leading_zero and i == 0) or (index == 0 and i == 0)

                res += dp(s, index + 1, new_tight, new_used, new_leading_zero)

            return res 

        res =  dp(s, 0, True, 0, True)
        # print(total)
        # print(good - set([str(int(t)) for t in total]))
        return res


240