LeetCode 题解工作台
最大公约数相等的子序列数量
给你一个整数数组 nums 。 请你统计所有满足以下条件的 非空 子序列 对 (seq1, seq2) 的数量: 子序列 seq1 和 seq2 不相交 ,意味着 nums 中 不存在 同时出现在两个序列中的下标。 seq1 元素的 GCD 等于 seq2 元素的 GCD。 Create the v…
4
题型
0
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 nums。
请你统计所有满足以下条件的 非空 子序列 对 (seq1, seq2) 的数量:
- 子序列
seq1和seq2不相交,意味着nums中 不存在 同时出现在两个序列中的下标。 seq1元素的 GCD 等于seq2元素的 GCD。
返回满足条件的子序列对的总数。
由于答案可能非常大,请返回其对 109 + 7 取余 的结果。
示例 1:
输入: nums = [1,2,3,4]
输出: 10
解释:
元素 GCD 等于 1 的子序列对有:
([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])
示例 2:
输入: nums = [10,20,30]
输出: 2
解释:
元素 GCD 等于 10 的子序列对有:
([10, 20, 30], [10, 20, 30])([10, 20, 30], [10, 20, 30])
示例 3:
输入: nums = [1,1,1,1]
输出: 50
提示:
1 <= nums.length <= 2001 <= nums[i] <= 200
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on updating DP states for each number and GCD combination, roughly O(n _maxVal^2). Space complexity is determined by storing counts for each possible GCD, O(n_ maxVal), where maxVal is the largest number in nums. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate correctly identifies the DP state representing subsequences and their GCDs.
- question_mark
Observe whether they optimize GCD updates instead of recomputing for all subsequences.
- question_mark
Look for awareness of subsequence pair counting and avoiding double counting.
常见陷阱
外企场景- error
Recomputing GCD for every subsequence instead of updating via DP.
- error
Counting subsequences incorrectly and including empty subsequences.
- error
Double counting pairs where order does not matter.
进阶变体
外企场景- arrow_right_alt
Count subsequences with equal LCM instead of GCD.
- arrow_right_alt
Find pairs of subsequences where the sum is equal rather than GCD.
- arrow_right_alt
Limit subsequences to length k and count pairs with equal GCD.