題目要求
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;
}