leetcode368. Largest Divisible Subset

12次阅读

共计 1005 个字符,预计需要花费 3 分钟才能阅读完成。

题目要求
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.

Example 1:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]

假设有一组值唯一的正整数数组,找到元素最多的一个子数组,这个子数组中的任选两个元素都可以构成 Si % Sj = 0 或 Sj % Si = 0。
思路和代码
这题最核心的思路在于,假如知道前面 k 个数字所能够组成的满足题意的最长子数组,我们就可以知道第 k + 1 个数字所能构成的最长子数组。只要这个数字是前面数字的倍数,则构成的数组的长度则是之前数字构成最长子数组加一。
这里我们使用了两个临时数组 count 和 pre,分别用来记录到第 k 个位置上的数字为止能够构成的最长子数组,以及该子数组的前一个可以被整除的值下标为多少。
public List<Integer> largestDivisibleSubset(int[] nums) {
int[] count = new int[nums.length];
int[] pre = new int[nums.length];
Arrays.sort(nums);
int maxIndex = -1;
int max = 0;
for(int i = 0 ; i<nums.length ; i++) {
count[i] = 1;
pre[i] = -1;
for(int j = i-1 ; j>=0 ; j–) {
if(nums[i] % nums[j] == 0 && count[j] >= count[i]){
count[i] = count[j] + 1;
pre[i] = j;
}
}
if(count[i] > max) {
max = count[i];
maxIndex = i;
}
}

List<Integer> result = new ArrayList<Integer>();
while(maxIndex != -1){
result.add(nums[maxIndex]);
maxIndex = pre[maxIndex];
}
return result;
}

正文完
 0