LeetCode 题解工作台
和带限制的子多重集合的数目
给你一个下标从 0 开始的非负整数数组 nums 和两个整数 l 和 r 。 请你返回 nums 中子多重集合的和在闭区间 [l, r] 之间的 子多重集合的数目 。 由于答案可能很大,请你将答案对 10 9 + 7 取余后返回。 子多重集合 指的是从数组中选出一些元素构成的 无序 集合,每个元素 …
4
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数组·哈希·扫描
答案摘要
class Solution: def countSubMultisets(self, nums: List[int], l: int, r: int) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的非负整数数组 nums 和两个整数 l 和 r 。
请你返回 nums 中子多重集合的和在闭区间 [l, r] 之间的 子多重集合的数目 。
由于答案可能很大,请你将答案对 109 + 7 取余后返回。
子多重集合 指的是从数组中选出一些元素构成的 无序 集合,每个元素 x 出现的次数可以是 0, 1, ..., occ[x] 次,其中 occ[x] 是元素 x 在数组中的出现次数。
注意:
- 如果两个子多重集合中的元素排序后一模一样,那么它们两个是相同的 子多重集合 。
- 空 集合的和是
0。
示例 1:
输入:nums = [1,2,2,3], l = 6, r = 6
输出:1
解释:唯一和为 6 的子集合是 {1, 2, 3} 。
示例 2:
输入:nums = [2,1,4,2,7], l = 1, r = 5
输出:7
解释:和在闭区间 [1, 5] 之间的子多重集合为 {1} ,{2} ,{4} ,{2, 2} ,{1, 2} ,{1, 4} 和 {1, 2, 2} 。
示例 3:
输入:nums = [1,2,1,3,5,2], l = 3, r = 5
输出:9
解释:和在闭区间 [3, 5] 之间的子多重集合为 {3} ,{5} ,{1, 2} ,{1, 3} ,{2, 2} ,{2, 3} ,{1, 1, 2} ,{1, 1, 3} 和 {1, 2, 2} 。
提示:
1 <= nums.length <= 2 * 1040 <= nums[i] <= 2 * 104nums的和不超过2 * 104。0 <= l <= r <= 2 * 104
解题思路
方法一
class Solution:
def countSubMultisets(self, nums: List[int], l: int, r: int) -> int:
kMod = 1_000_000_007
# dp[i] := # of submultisets of nums with sum i
dp = [1] + [0] * r
count = collections.Counter(nums)
zeros = count.pop(0, 0)
for num, freq in count.items():
# stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ...
stride = dp.copy()
for i in range(num, r + 1):
stride[i] += stride[i - num]
for i in range(r, 0, -1):
if i >= num * (freq + 1):
# dp[i] + dp[i - num] + dp[i - freq * num]
dp[i] = stride[i] - stride[i - num * (freq + 1)]
else:
dp[i] = stride[i]
return (zeros + 1) * sum(dp[l : r + 1]) % kMod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of dynamic programming and hash map usage in counting subsets.
- question_mark
Test for optimization techniques when handling large arrays and sums, such as using frequency counts.
- question_mark
Assess the candidate's ability to handle modular arithmetic efficiently in large numbers.
常见陷阱
外企场景- error
Failing to properly count subsets with repeated elements can lead to incorrect results.
- error
Inefficient range counting methods may lead to time limit exceeded errors.
- error
Overlooking the modulo constraint may result in integer overflow or incorrect final answers.
进阶变体
外企场景- arrow_right_alt
Modify the problem to count only subsets where all elements are distinct.
- arrow_right_alt
Change the sum range to be exclusive, not inclusive.
- arrow_right_alt
Introduce constraints on the number of elements in each subset and track those as well.