LeetCode[368] Largest Divisible Subset

来源:互联网 发布:小米手环数据修改攻略 编辑:程序博客网 时间:2024/04/20 06:58

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]

vector<int> largestDivisibleSubset(vector<int>& nums){    if (nums.size() == 0) return{};    sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });    int len = nums.size(), curMax = 1, k = 0;    vector<int> par(len), dp(len, 1), result;    for (int i = 0; i < len; i++) par[i] = i;    for (int i = 1; i < len; i++)    {        for (int j = 0; j < i; j++)        {            if (nums[j] % nums[i] != 0) continue;            if (dp[i] < dp[j] + 1)                 par[i] = j, dp[i] = dp[j] + 1;            if (dp[i] > curMax) curMax = dp[i], k = i;        }    }    while (par[k] != k)    {        result.push_back(nums[k]);        k = par[k];    }    result.push_back(nums[k]);    return result;}
0 0