题目:
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]
思路:
一道中等难度的动态规划题目。首先对数组进行排序,然后定义dp[i]表示以第i个元素为结尾的子集的最大长度,那么状态转移方程为:dp[i] = max(dp[j] + 1),其中j < i并且nums[i] % nums[j] == 0。由于题目要求返回该子串,所以还需要定义一个数组记录每个元素的上一个元素。在计算出所有的dp之后,我们遍历找出最大值,并从该值开始回溯,构造出所要求的子串。该算法的时间复杂度是O(n^2),空间复杂度是O(n)。
代码:
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
if(nums.size() == 0) {
return {};
}
vector<int> ret;
sort(nums.begin(), nums.end());
vector<int> dp(nums.size(), 1);
vector<int> last_index(nums.size(), -1);
for(int i = 1; i < nums.size(); ++i) { // dynamic programming
for(int j = i - 1; j >= 0; --j) {
if(nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
last_index[i] = j;
}
}
}
int max_length = 1, max_index = 0;
for(int i = 1; i < dp.size(); ++i) { // find the one with largest length
if(dp[i] > max_length) {
max_length = dp[i];
max_index = i;
}
}
while(max_index != -1) { // reconstruct the array
ret.push_back(nums[max_index]);
max_index = last_index[max_index];
}
reverse(ret.begin(), ret.end());
return ret;
}
};