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:


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]


解体思路

首先我们根据条件Si % Sj = 0 or Sj % Si = 0可以推出,最大可整除子集中任意两个数一定有一个数可以被可以另一个数整除。
也就是说,将这些数按从小到大的顺序排列,则后一个数一定可以被前一个数整除!
于是问题转换为了类似于最长不下降子序列的DP。


代码

class Solution {
public:
    vector largestDivisibleSubset(vector& nums) {
        sort(nums.begin(),nums.end());
        
        int len = nums.size();
        int ans = 0, ansi;
        int dp[len];
        int pre[len];//用于保存最长可整除序列的路径
        for (int i=0;idp[i]){
                    dp[i] = dp[j]+1; pre[i] = j;
                }
            }
            if (dp[i] > ans){
                ans = dp[i]; ansi = i;
            }
        }
        //找出最长可整除子序列,方法类似于最长不下降子序列
        vector res;
        for (int i=1;i<=ans;i++){
            res.push_back(nums[ansi]); ansi = pre[ansi];
        }
        //利用pre数组找到最长可整除子序列
        sort(res.begin(),res.end());
        return res;
    }
};

你可能感兴趣的:(368 Largest Divisible Subset)