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.
Personal tips: DP算法。数组排序后,假设j大于i,nums[j]%nums[i]=0,利用a[i]=j储存位置关系并保存最长子串的最小位数pos。代码如下:
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums)
{
if (nums.empty()) return nums;
sort(nums.begin(), nums.end());
int m = nums.size();
vector<int> subset{}; vector<int> length(m, 0); vector<int> a(m, m); int max = 0,pos=0;
for (int i = m - 1; i >= 0; i--)
{
for (int j = i; j < m; j++)
{
if (nums[j] % nums[i] == 0 && length[i] < length[j] + 1)
{
length[i] = length[j] + 1;
a[i] = j;
if (max < length[i])
{
max = length[i];
pos = i;
}
}
}
}
int next;
subset.push_back(nums[pos]);
while (pos < m)
{
next = a[pos]; if (pos == next) break;
subset.push_back(nums[next]);
pos = next;
}
return subset;
}
};