LeetCode第138双周赛T3

统计好整数的数目
枚举所有回文数,然后判断能否整除。
如何避免重复:把所有数字转为字符串然后排序。
如何计数:把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;
        
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值