LeetCode 题解工作台
最大整除子集
给你一个由 无重复 正整数组成的集合 nums ,请你找出并返回其中最大的整除子集 answer ,子集中每一元素对 (answer[i], answer[j]) 都应当满足: answer[i] % answer[j] == 0 ,或 answer[j] % answer[i] == 0 如果存在…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们先对数组进行排序,这样可以保证对于任意的 $i \lt j$,如果 可以整除 ,那么 一定在 的左边。 接下来,我们定义 表示以 为最大元素的最大整除子集的大小,初始时 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
nums ,请你找出并返回其中最大的整除子集 answer ,子集中每一元素对 (answer[i], answer[j]) 都应当满足:
answer[i] % answer[j] == 0,或answer[j] % answer[i] == 0
如果存在多个有效解子集,返回其中任何一个均可。
示例 1:
输入:nums = [1,2,3] 输出:[1,2] 解释:[1,3] 也会被视为正确答案。
示例 2:
输入:nums = [1,2,4,8] 输出:[1,2,4,8]
提示:
1 <= nums.length <= 10001 <= nums[i] <= 2 * 109nums中的所有整数 互不相同
解题思路
方法一:排序 + 动态规划
我们先对数组进行排序,这样可以保证对于任意的 ,如果 可以整除 ,那么 一定在 的左边。
接下来,我们定义 表示以 为最大元素的最大整除子集的大小,初始时 。
对于每一个 ,我们从左往右枚举 ,如果 可以被 整除,那么 可以从 转移而来,我们更新 。过程中,我们记录 的最大值的下标 以及对应的子集大小 。
最后,我们从 开始倒序遍历,如果 可以被 整除,且 ,那么 就是一个整除子集的元素,我们将 加入答案,并将 减 ,同时更新 。继续倒序遍历,直到 。
时间复杂度 ,空间复杂度 。其中 是数组的长度。
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
f = [1] * n
k = 0
for i in range(n):
for j in range(i):
if nums[i] % nums[j] == 0:
f[i] = max(f[i], f[j] + 1)
if f[k] < f[i]:
k = i
m = f[k]
i = k
ans = []
while m:
if nums[k] % nums[i] == 0 and f[i] == m:
ans.append(nums[i])
k, m = i, m - 1
i -= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) due to the nested iteration for each element to check divisibility against prior elements. Space complexity is O(n) for the dp and prev arrays storing subset lengths and backtracking information. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks about efficient subset building beyond brute force.
- question_mark
Wants you to recognize the dynamic programming state transition pattern.
- question_mark
May probe alternative reconstruction methods and edge cases.
常见陷阱
外企场景- error
Forgetting to sort nums can break the divisibility chain.
- error
Incorrectly updating dp without checking all previous divisible elements.
- error
Failing to reconstruct the subset using prev pointers after computing dp.
进阶变体
外企场景- arrow_right_alt
Return all largest divisible subsets if multiple exist.
- arrow_right_alt
Handle negative integers or zero with adjusted divisibility rules.
- arrow_right_alt
Optimize for space using only a single array with backtracking reconstruction.