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。

相关推荐
Allen_LVyingbo8 分钟前
自进化医疗智能体:动态记忆与持续运行的Python架构编程(上)
数据结构·python·架构·动态规划·健康医疗
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #45:跳跃游戏II(贪心法、动态规划、BFS等多种实现方案详解)
算法·leetcode·贪心算法·动态规划·bfs·java面试·跳跃游戏ii
Boop_wu13 小时前
[Java 算法] 动态规划(1)
算法·动态规划
云淡风轻~窗明几净18 小时前
关于TSP的海岸线猜想:SeaLine算法的逐层法(不同于逐点法)
数据结构·算法·动态规划·模拟退火算法
hnjzsyjyj20 小时前
洛谷 P1192:台阶问题 ← 动态规划 + 前缀和优化
前缀和·动态规划·差分
cpp_25011 天前
P8395 [CCC 2022 S1] Good Fours and Good Fives
数据结构·c++·算法·动态规划·图论·题解·洛谷
VelinX1 天前
【个人学习||算法】动态规划
学习·算法·动态规划
Boop_wu1 天前
[Java 算法] 动态规划2
算法·leetcode·动态规划
Allen_LVyingbo1 天前
“拓扑量子计算被证伪”科学纠偏事件分析
算法·搜索引擎·全文检索·动态规划·创业创新·量子计算
Sakinol#2 天前
Leetcode Hot 100 ——动态规划part02
算法·leetcode·动态规划