- Leetcode 3352. Count K-Reducible Numbers Less Than N
- 1. 解题思路
- 2. 代码实现
- 题目链接:3352. Count K-Reducible Numbers Less Than N
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代码实现如下:
MOD = 10**9+7factorials = [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]) % MODclass Solution:def countKReducibleNumbers(self, s: str, k: int) -> int:if s == "1":return 0def minus_one(s):n = len(s)idx = n-1while s[idx] == "0":idx -= 1s = 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 0if ones == 0:return 1if idx >= n:return 0if allow_large:return (count(idx+1, ones-1, allow_large) + count(idx+1, ones, allow_large)) % MODelif s[idx] == "1":return (count(idx+1, ones-1, allow_large) + count(idx+1, ones, True)) % MODelse:return count(idx+1, ones, allow_large)ans = 0for digit_num in digit_nums.values():for digit in digit_num:ans = (ans + count(0, digit, False)) % MODreturn ans
提交代码评测得到:耗时1513ms,占用内存438.4MB。