classSolution {
public:int numDupDigitsAtMostN(int n) {
vector<int> digits;
int x = n;
while (x) {
digits.push_back(x %10);
x /=10;
}
reverse(digits.begin(), digits.end());
int k = digits.size(), ans =0;
// Count unique-digit numbers with length < k
for (int i =1; i < k; ++i) {
int cnt =9;
for (int j =1; j < i; ++j) cnt *= (10-j);
ans += cnt;
}
// Count unique-digit numbers with length == k
function<int(int, int, bool, bool)> dfs = [&](int pos, int mask, bool tight, bool leading) ->int {
if (pos == k) return leading ?1:0;
int res =0;
int up = tight ? digits[pos] :9;
for (int d =0; d <= up; ++d) {
if (leading && d ==0) {
res += dfs(pos+1, mask, tight && d==up, true);
} elseif (!(mask & (1<<d))) {
res += dfs(pos+1, mask | (1<<d), tight && d==up, false);
}
}
return res;
};
ans += dfs(0, 0, true, true);
return n - ans +1;
}
};
classSolution {
funnumDupDigitsAtMostN(n: Int): Int {
val digits = mutableListOf<Int>()
var x = n
while (x > 0) {
digits.add(0, x % 10)
x /=10 }
val k = digits.size
var ans = 0for (i in1 until k) {
var cnt = 9for (j in1 until i) cnt *= (10-j)
ans += cnt
}
fundfs(pos: Int, mask: Int, tight: Boolean, leading: Boolean): Int {
if (pos == k) returnif (leading) 1else0var res = 0val up = if (tight) digits[pos] else9for (d in0..up) {
if (leading && d ==0) {
res += dfs(pos+1, mask, tight && d==up, true)
} elseif (mask and (1 shl d) ==0) {
res += dfs(pos+1, mask or (1 shl d), tight && d==up, false)
}
}
return res
}
ans += dfs(0, 0, true, true)
return n - ans + 1 }
}
classSolution:
defnumDupDigitsAtMostN(self, n: int) -> int:
digits = list(map(int, str(n)))
k, ans = len(digits), 0for i in range(1, k):
cnt =9for j in range(1, i):
cnt *= (10-j)
ans += cnt
defdfs(pos: int, mask: int, tight: bool, leading: bool) -> int:
if pos == k:
return1if leading else0 res =0 up = digits[pos] if tight else9for d in range(0, up+1):
if leading and d ==0:
res += dfs(pos+1, mask, tight and d==up, True)
elifnot (mask & (1<<d)):
res += dfs(pos+1, mask | (1<<d), tight and d==up, False)
return res
ans += dfs(0, 0, True, True)
return n - ans +1