Given a set of distinct positive integers nums
, return the largest subset answer
such that every pair (answer[i], answer[j])
of elements in this subset satisfies:
answer[i] % answer[j] == 0
, oranswer[j] % answer[i] == 0
If there are multiple solutions, return any of them.
Example 1:
Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.
Example 2:
Input: nums = [1,2,4,8]
Output: [1,2,4,8]
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 109
- All the integers in
nums
are unique.
Problem Analysis:
For simplicity, we can first sort the array. Then suppose we obtain such a subset, it is a subarray, then for every i, j < subarray size, and i < j, subarray[j] % subarray[i] == 0.
So we can scan the array, record the largest subset, it is the result we wanted.
Solution
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<pair<int, int>> dp(nums.size(), make_pair(-1, -1));
int length = 0;
int last = -1;
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[j] % nums[i] == 0) {
if (dp[j].first == -1) {
dp[j] = make_pair(2, i);
if (dp[j].first > length) {
length = dp[j].first;
last = j;
}
} else if (dp[i].first >= dp[j].first) {
dp[j] = make_pair(dp[i].first + 1, i);
if (dp[j].first > length) {
length = dp[j].first;
last = j;
}
}
}
}
}
if (length == 0) return {nums[0]};
vector<int> res;
while (last != -1) {
res.push_back(nums[last]);
last = dp[last].second;
}
reverse(res.begin(), res.end());
return res;
}
};
time complexity is O(n²)
Space complexity is O(n)