Given a set of distinct positive integers, find the largest subset such that every pair (,
) of elements in this subset satisfies:
%
= 0 or
%
= 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]
题意 :找出给出数组中最大可除子集,要求子集中的任意一对数 (,
) 都能满足
%
= 0 or
%
= 0.
思路:
1.由于输入的数组是无序的,所以要先将数组进行排序;
2.利用动态规划的思想,从头开始遍历整个数组,当遍历到某个数x时,将这个数除以它之前的每个数,当x能被前面的某个数y整除时,再判断此时y的可除子集的个数,若y是x前面所有数中子集最大的数,那x的可除子集个数=y的可除子集个数+1(x自身);
3.用一个数maxLength记录最大可除子集的长度;
maxIndex记录最大可除子集最后一位数的坐标;
用与输入数组等长的数组remainder[]记录每个数的最大可除子集大小 ,如下图;
用与输入数组等长的数组pre[]记录每个数所在的最大可除子集中的前一个数。每当遍历完一个数x后,若x的可除子集是当前最大的,便用maxLength记录,并且当前数的坐标用maxIndex记录;并且将x所在可除子集的前一个数y的坐标 j 记录在pre数组中:。
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
nums | 2 | 3 | 4 | 6 | 7 | 8 | 9 |
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
remainder | 0 | 0 | 1 | 1 | 0 | 2 | 1 |
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
pre | -1 | -1 | 0 | 1 | -1 | 2 | 1 |
代码:
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int len = nums.length;
List<Integer> result = new ArrayList<Integer>();
int[] Remainder = new int[len]; //记录可除子集数大小
int[] pre = new int[len]; //可除子集中前一个数的坐标
int maxLen = 0; //最大可除子集的长度
int maxIndex=0; //最长可除子集最后一位数的坐标
if(len==0)
return result;
Arrays.sort(nums);
for(int i=1;i<len;i++){
for(int j=i-1;j>=0;j--){
if(nums[i]%nums[j]==0 && Remainder[j]>=Remainder[i]){
//能整除且可除子集个数更大,则更新当前数可除子集的大小
Remainder[i] = Remainder[j]+1;
//记录j为i所在可除子集的前一个数
pre[i]=j;
}
}
if(Remainder[i]>maxLen){
maxIndex = i;
maxLen = Remainder[i];
}
}
int index = maxIndex;
while(maxLen-- >= 0){
result.add(0,nums[index]); //List.add(0,value):将数插在数组的最前面
index = pre[index];
}
return result;
}
}