[LeetCode] Count Numbers with Unique Digits

357. Count Numbers with Unique Digits

Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int dp[10][1<<10];
int helper(int mask, int n) {
if(__builtin_popcount(mask) == n) return 1;
if(dp[n][mask] != -1) return dp[n][mask];
int& res = dp[n][mask] = 0;
for(int i = mask ? 0 : 1; i <= 9; i++) {
if(mask & (1<<i)) continue;
res += helper(mask | (1<<i), n);
}
return res;
}
public:
int countNumbersWithUniqueDigits(int n) {
memset(dp, -1, sizeof dp);
int res = 0;
for(int i = 0; i <= n; i++)
res += helper(0, i);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/29/PS/LeetCode/count-numbers-with-unique-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.