1. 程式人生 > >LeetCode 368: Largest Divisible Subset

LeetCode 368: Largest Divisible Subset

368. Largest Divisible Subset

Difficulty: Medium
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]

思路

本題是要找到陣列的最大可整除的子集。
首先對無序的陣列進行排序,依次遍歷陣列元素;
用排在當前元素前的每個數去整除該元素;
若可整除,則找到一個當前元素為最大倍數的可整除子集,該子集的元素個數為除數的最大子集個數加一,且該子集中排在當前元素前一位的數為除數,所有可整除子集中元素最多的子集為該元素的最大可整除子集;
所有元素的最大可整除子集中元素最多的即為最終結果。

程式碼

[C++]

class Solution {
public:
    vector<int>
largestDivisibleSubset(vector<int>& nums) { vector<int> res; if (nums.size() == 0) return res; sort(nums.begin(), nums.end()); vector<int> len(nums.size(), 1); vector<int> son(nums.size(), 0); int largest = 0; int
largesti = 0; for (int i = 0; i < nums.size(); ++i) { for (int j = 0; j < i; ++j) { if (nums[i] % nums[j] == 0 && len[i] < len[j] + 1) { len[i] = len[j] + 1; son[i] = j; } } if (largest < len[i]) { largesti = i; largest = len[i]; } } for (int i = 0; i < largest; ++i) { res.insert(res.begin(), nums[largesti]); largesti = son[largesti]; } return res; } };