Largest Divisible Subset
https://leetcode.com/problems/largest-divisible-subset/description/
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Thoughts
如果这道题只是问最长的能互相除的子序列是什么,会简洁很多,思路和LIS相似。让f[i]表示以i为尾的互除子序列,f[i]初始值为1,因为它能除自身。然后遍历所有已经遍历过了的看nums[i]是否能整除nums[j], 如果可以整除则把f[j] + 1和现有f[i]比较取最大值。这题比较麻烦的是不但让你返回最大长度,还要求返回完整的序列。因此我们用一个array记录下对于f[i]找到的最大的j。然后就能从尾往前回溯得到目标序列了。
Code
Analysis
Errors:
max = f[i];忘了写
res.add(nums[subres])写在了map.get后
没有排序
做题耗时50min
时间复杂度O(n^2).
Last updated
Was this helpful?