统计好整数的数目
枚举所有回文数,然后判断能否整除。
如何避免重复:把所有数字转为字符串然后排序。
如何计数:把n个数字,放到n个位置,总共有n!
种方案,并且相同数字内部不需要有顺序,所有对于每种数字,除去cnt[i]!
,另外,第一个位置不能放0,所有方案数就是(n-cnt[0]) * factorial[n-1) / cnt[i]!
typedef long long LL;
class Solution {
public:
long long countGoodIntegers(int n, int k) {
vector<LL> factorial(n + 1,1);
for(int i = 1; i <= n; i ++)factorial[i] = factorial[i-1] * i;
LL base = pow(10, (n - 1) / 2);
unordered_set<string> mp;
LL ans = 0;
for(int i = base; i < 10 * base; i ++)
{
string s = to_string(i);
s = s + string(s.rbegin() + (n % 2), s.rend());
if(stoll(s) % k != 0)continue;
sort(s.begin(),s.end());
if(mp.find(s) != mp.end())continue;
mp.insert(s);
int cnt[10]{};
for(auto c : s){cnt[c-'0']++;}
LL res = (n-cnt[0]) * factorial[n-1];
for(int i = 0; i < 10; i ++)res /= factorial[cnt[i]];
ans += res;
}
return ans;
}
};