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。

相关推荐
_小苔藓_42 分钟前
初探动态规划--记忆化搜索
深度优先·动态规划·代理模式
维齐洛波奇特利(male)6 小时前
(动态规划 完全背包 **)leetcode279完全平方数
算法·动态规划
lisanndesu16 小时前
动态规划
算法·动态规划
诚丞成2 天前
斐波那契数列模型:在动态规划的丝绸之路上追寻斐波那契的足迹(下)
算法·动态规划
不想编程小谭2 天前
力扣LeetCode: 931 下降路径最小和
数据结构·c++·算法·leetcode·动态规划
Perishell2 天前
无人机避障——感知篇(采用Livox-Mid360激光雷达获取点云数据显示)
linux·机器人·动态规划·无人机·slam
诚丞成3 天前
斐波那契数列模型:在动态规划的丝绸之路上追寻斐波那契的足迹(上)
算法·动态规划
孑么4 天前
力扣 买卖股票的最佳时机
算法·leetcode·职场和发展·贪心算法·动态规划
孑么4 天前
力扣 跳跃游戏 II
java·算法·leetcode·职场和发展·贪心算法·动态规划
斯内科5 天前
C#使用文件读写操作实现仙剑五前传称号存档修改
c#·二进制·修改器