给你一个由 无重复 正整数组成的集合 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 <= 1000
1 <= nums[i] <= 2 * 109
nums
中的所有整数 互不相同
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
f, p = [0] * n, [0] * n
for i in range(n):
l, pre = 1, i
for j in range(n):
if nums[i] % nums[j] == 0 and f[j] + 1 > l:
l = f[j] + 1
pre = j
f[i] = l
p[i] = pre
max_len, max_index = 0, 0
for i, v in enumerate(f):
if max_len < v:
max_len = v
max_index = i
ans = []
while len(ans) < max_len:
ans.append(nums[max_index])
max_index = p[max_index]
return ans[::-1]
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int[] f = new int[n], p = new int[n];
for (int i = 0; i < n; i++) {
int l = 1, pre = i;
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && f[j] + 1 > l) {
l = f[j] + 1;
pre = j;
}
}
f[i] = l;
p[i] = pre;
}
int maxLen = 0, maxIndex = 0;
for (int i = 0; i < n; i++) {
if (f[i] > maxLen) {
maxLen = f[i];
maxIndex = i;
}
}
List<Integer> ans = new ArrayList<>();
while (ans.size() < maxLen) {
ans.add(nums[maxIndex]);
maxIndex = p[maxIndex];
}
Collections.reverse(ans);
return ans;
}
}