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:
nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8] Result: [1,2,4,8]
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
找出最长的子数组,使得数组中的任意两个数的模为0(大的数模小的数)
首先给原始数组排序。创建一个数组record,记录以每一个数字结尾的子数组的解是多少。创建一个字典,用来记录每一个数字能够整除的最大的数,即排在这个数前面的第一个数。
对于第i位的数num[i],判断它前面的i-1个数num[j],如果num[j]可以整除num[i],那么record[i] = max{record[i], record[j] + 1},如果record[i]更新了,那么字典里num[i]对应的记录要修改为num[j]。
最后从最大的num[i]开始,每一次找到前一个数,放到数组中,即为解。
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Arrays.sort(nums);
int len = nums.length;
if(len == 0)
return new ArrayList<Integer>();
int[] record = new int[len];
int max = -1;
for(int i = 0; i < len; i++){
int temp = -1;
for(int j = i - 1; j > -1; j--){
if(nums[i] % nums[j] == 0){
if(temp == -1 || record[j] > record[temp])
temp = j;
}
}
if(temp == -1)
record[i] = 1;
else{
record[i] = record[temp] + 1;
map.put(nums[i], nums[temp]);
}
if(max == -1 || record[i] > record[max])
max = i;
}
List<Integer> list = new ArrayList<Integer>();
list.add(nums[max]);
max = nums[max];
while(map.containsKey(max)){
max = map.get(max);
list.add(max);
}
return list;
}
}