LeetCode 2376. 统计特殊整数

这篇博客介绍了如何使用数位DP(动态规划)方法解决LeetCode题目2376,涉及计算特殊整数的数量。通过递归和状态转移方程,展示了如何遍历每一位并更新状态来求解问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 2376. 统计特殊整数
在这里插入图片描述
数位DP (灵神模板)

const int N = 10;
class Solution {
public:
    int f[N][1 << N];
    int n;
    string s;
    // u: 当前位, status : 标记每一个数字是否被用过
    // limit : 当前位是否受限制, first : 是否为第一位数字, 不能有前导0 
    int dfs(int u, int status, bool limit, bool first)
    {
        if(u == n) return first == false;
        if(!limit && !first && f[u][status] >= 0) return f[u][status];
        int res = 0;
        if(first) // 是第一位数字,可以跳过
            res += dfs(u + 1, status, false, true);
        for(int i = first, up = limit ? s[u] - '0' : 9; i <= up; i ++)
        {
            if((status >> i & 1) == 0)
                res += dfs(u + 1, status | (1 << i), limit && i == up, false);
        }
        if(!limit && !first) f[u][status] = res;
        return res;
    }
    int countSpecialNumbers(int n) {
        memset(f, -1, sizeof f);
        s = to_string(n);
        this -> n = s.size();
        return dfs(0, 0, true, true);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值