[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.

 

这道题给了我们一个数组,让我们求这样一个子集合,集合中的任意两个数相互取余均为0,而且提示中说明了要使用DP来解。那么我们考虑,较小数对较大数取余一定为0,那么问题就变成了看较大数能不能整除这个较小数。那么如果数组是无序的,处理起来就比较麻烦,所以我们首先可以先给数组排序,这样我们每次就只要看后面的数字能否整除前面的数字。我们可以从前往后遍历数数,对于每个遍历到的数字,再从此位置向前遍历到开头,再这个过程中把所有能被当前数字整除的值都存入一个临时数组t中,然后遍历到开头后,然后更新结果数组res,参见代码如下:

 

解法一:

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

 

我们也可以开始就从后面往前遍历,然后对于每个数字都要单独遍历到开头,类似一种冒泡排序的思路,参见代码如下;

 

解法二:

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

 

参考资料:

https://leetcode.com/discuss/111015/java-o-n-2-nested-loops

https://leetcode.com/discuss/110845/java-solution-in-32ms-o-n-2-time-o-n-space

 

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

你可能感兴趣的:([LeetCode] Largest Divisible Subset 最大可整除的子集合)