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。

相关推荐
Pniubi12 天前
动态规划入门 ( - 力扣509斐波那契数)
算法·动态规划
上海潭龙东海科技有限公司13 天前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
俊俊几年的13 天前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c
小此方17 天前
[算法实战论:动态规划]背包问题概念,01不满背包问题,01满背包问题,背包问题的滚动数组空间优化
算法·动态规划
冻柠檬飞冰走茶19 天前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
Dream it possible!20 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
小此方20 天前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
-梅20 天前
算法(1) 动态规划
算法·动态规划
UIU11421 天前
P1481 魔族密码
c++·算法·动态规划
j7~25 天前
【动态规划算法专题】动态规划五部曲实战:泰波那契数、三步问题、最小花费爬楼梯
c++·算法·动态规划·数据结构与算法