难度中等299
给你一个由 无重复 正整数组成的集合 nums
,请你找出并返回其中最大的整除子集 answer
,子集中每一元素对 (answer[i], answer[j])
都应当满足:
answer[i] % answer[j] == 0
,或answer[j] % answer[i] == 0
如果存在多个有效解子集,返回其中任何一个均可。
思路:
考虑若子数组为从小到大排序后的,则当前数组满足上述的要求,则后一个数为该数组后续的充要条件为:后一个数可以整除数组中的最大数;
需要额外考虑下列情况:
若数组中存在多组上述子数组如 data = [ 1,2,3,4,9, 27],满足的条件为 [ 1,2,4 ] 和 [ 1,3,9,27],最长数组的结果为后者。
考虑对任意数记录当前数据求解满足上述条件子序列的数量 如上述数组结果为: size = [ 1,2,2,3,3,4 ]
对任意数记录当前数满足上述条件子序列时前一个数据的结果, 如上述结果为: last = [ 0,0,0,1,2,4 ]
重建子数组的方式为: 子序列数量最大处的位置开始计算数组位置:
上述结果提取顺序为: cur = 5 size[cur] = 4 last[cur] = 4 取 data[5] = 27 加入结果数组中:
后续: cur = last[cur] = 4 size[cur] = 3 last[cur] = 2 取 data[4] = 9 加入结果数组中。(重复上述操作,直到 size[cur] = 1 后结束)
代码:
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(),nums.end());
int len=nums.size();
vector<int> size(len,0);
vector<int> last(len,0);
int res=0;
vector<int> ans;
for(int i=0;i<len;++i){
int tem = 1,pre = i;
for(int j=0;j<i;++j){
if(nums[i] % nums[j] ==0 && size[j]>=tem){
tem = size[j]+1;
pre=j;
}
}
size[i]=tem;
last[i]=pre;
}
int idx = max_element(size.begin(), size.end()) - size.begin();
int max = size[idx];
while(ans.size() != max){
ans.push_back(nums[idx]);
idx = last[idx];
}
reverse(ans.begin(),ans.end());
return ans;
}