Leetcode 3352. Count K-Reducible Numbers Less Than N

  • [Leetcode 3352. Count K-Reducible Numbers Less Than N](#Leetcode 3352. Count K-Reducible Numbers Less Than N)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的话思路上我是拆成了两步来做的,首先,我们要认识到,这里的变化本质就是看数的二进制表达当中有多少个1,因此,假设给定数字的二进制表示长度为 n n n,我们就是要遍历 1 1 1到 n n n当中有多少数能够在至多 k k k次变换之后变为 1 1 1,显然 k = 1 k=1 k=1时,答案就只有 1 1 1,也就是数字只能包含一个二级位为 1 1 1,然后,对于其他的数,我们只需要用一个迭代遍历即可快速获取,整体的复杂度就是 O ( k n ) O(kn) O(kn)。

然后,剩下的问题就变成了,一直一个数二进制数包含 m m m个 1 1 1,请问一共有多少个不大于给定值 s s s的数,此时我们用一个动态规划即可完成。

2. 代码实现

给出python代码实现如下:

python 复制代码
MOD = 10**9+7

factorials = [1 for _ in range(801)]
for i in range(2, 801):
    factorials[i] = (i * factorials[i-1]) % MOD
revs = [pow(i, -1, mod=MOD) for i in factorials]

@lru_cache(None)
def C(n, m):
    return (factorials[n] * revs[m] * revs[n-m]) % MOD

class Solution:
    def countKReducibleNumbers(self, s: str, k: int) -> int:
        if s == "1":
            return 0
        
        def minus_one(s):
            n = len(s)
            idx = n-1
            while s[idx] == "0":
                idx -= 1
            s = s[:idx] + "0" + "1" * (n-idx-1)
            return s.lstrip("0")
        
        s = minus_one(s)
        n = len(s)
        
        digit_nums = defaultdict(set)
        digit_nums[1] = {1}
        for i in range(2, k+1):
            for j in range(2, n+1):
                if Counter(bin(j))["1"] in digit_nums[i-1]:
                    digit_nums[i].add(j)

        @lru_cache(None)
        def count(idx, ones, allow_large):
            if allow_large:
                return C(n-idx, ones) if n-idx >= ones else 0
            if ones == 0:
                return 1
            if idx >= n:
                return 0
            if allow_large:
                return (count(idx+1, ones-1, allow_large) + count(idx+1, ones, allow_large)) % MOD
            elif s[idx] == "1":
                return (count(idx+1, ones-1, allow_large) + count(idx+1, ones, True)) % MOD
            else:
                return count(idx+1, ones, allow_large)
            
        ans = 0
        for digit_num in digit_nums.values():
            for digit in digit_num:
                ans = (ans + count(0, digit, False)) % MOD
        return ans

提交代码评测得到:耗时1513ms,占用内存438.4MB。

相关推荐
wabs66614 小时前
关于动态规划【力扣343.整数拆分的递推公式怎么理解?】
算法·leetcode·动态规划
珊瑚里的鱼14 小时前
【动态规划】买卖股票的最佳时机含手续费
算法·动态规划
随意起个昵称15 小时前
线性dp-LIS题目6(友好城市,二分优化)
算法·动态规划
8Qi81 天前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
wabs6661 天前
关于动态规划【力扣63.不同路径II与62.不同路径的区别(C++)】自我总结
动态规划
三千里2 天前
路径规划算法-备忘
算法·自动驾驶·动态规划
2601_961845152 天前
新高考一卷真题2025|真题PDF全科整理
线性代数·矩阵·pdf·动态规划·概率论·高考
随意起个昵称2 天前
线性dp-LIS题目5(导弹拦截,二分优化)
c++·算法·动态规划
8Qi82 天前
LeetCode 5:最长回文子串(Longest Palindromic Substring)—— 题解
算法·leetcode·职场和发展·动态规划
8Qi82 天前
LeetCode 1143 & 718:最长公共子序列 / 最长重复子数组
算法·leetcode·职场和发展·动态规划