LeetCode 368. Largest Divisible Subset

来源:互联网 发布:淘宝账号花钱解封 编辑:程序博客网 时间:2024/05/01 22:29

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]

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


0 0