# [LeetCode] Largest Divisible Subset 最大可整除的子集合

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.

class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> dp(nums.size(), 0), parent(nums.size(), 0), res;
int mx = 0, mx_idx = 0;
for (int i = nums.size() - 1; i >= 0; --i) {
for (int j = i; j < nums.size(); ++j) {
if (nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
parent[i] = j;
if (mx < dp[i]) {
mx = dp[i];
mx_idx = i;
}
}
}
}
for (int i = 0; i < mx; ++i) {
res.push_back(nums[mx_idx]);
mx_idx = parent[mx_idx];
}
return res;
}
};

class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> res;
vector<pair<int, int>> dp(nums.size());
int mx = 0, mx_idx = 0;
for (int i = 0; i < nums.size(); ++i) {
for (int j = i; j >= 0; --j) {
if (nums[i] % nums[j] == 0 && dp[i].first < dp[j].first + 1) {
dp[i].first = dp[j].first + 1;
dp[i].second = j;
if (mx < dp[i].first) {
mx = dp[i].first;
mx_idx = i;
}
}
}
}
for (int i = 0; i < mx; ++i) {
res.push_back(nums[mx_idx]);
mx_idx = dp[mx_idx].second;
}
return res;
}
};

https://discuss.leetcode.com/topic/49580/c-o-n-2-solution-56ms

https://discuss.leetcode.com/topic/49456/c-solution-with-explanations/2

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2016-06-28 22:23  Grandyang  阅读(16550)  评论(7编辑  收藏  举报