2376. Count Special Integers

Created 08/14/2022

We call a positive integer special if all of its digits are distinct.

Given a positive integer n, return the number of special integers that belong to the interval [1, n].

Example 1:

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

Example 2:

Input: n = 5
Output:
 5
Explanation:
 All the integers from 1 to 5 are special.

Example 3:

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

Constraints:

  • 1 <= n <= 2 * 109

Basic Idea

静下心来,分情况讨论,计算总共的数字个数。

  1. 首先考虑位数小于n的所有数字,这种情况下对于使用什么数字完全没有限制,只需要保证不重复即可。如果n=1234,则共有 9*9*8 + 9*9 + 9 个满足条件的三位以下的数字。

  2. 接下来考虑位数和n相同的情况:

    1. 对第i位考虑该位小于n中第i位的情况,这种情况下剩余的位可以任意取值

    2. 之后考虑第i位和n中第i位相同的情况,此时需要将该数字标记为已经使用,然后继续考虑后面一位

Java Code:

Last updated