[WXM] LeetCode 368. Largest Divisible Subset C++

368. 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:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)

Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]

Approach

  1. 题目大意就是找出一组最长的并且任意两两其中一个可以整除另一个的数组。其实你会发现这种数组是某个数的倍数,不断上升,所以我们抓住这个性质,我们就可以很好的解题,我们只要对数组从小到大排个序,那么我们就只用考虑小的能整除大的数即可,那么其实就是找上升子序列了,因为要记录轨迹,所以有两种版本,一个并查集版,还有一个简单粗暴版。

Code

简单粗暴版

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

并查集版

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

你可能感兴趣的:([WXM] LeetCode 368. Largest Divisible Subset C++)