Divisible by each other? Maximum number!
Title :
given a set of positive integers without duplication composition, divisible find the largest subset, subset any pair (Si, Sj) must be satisfied: Si% Sj = 0 or Sj% Si = 0.
Sample :
Example 1:
Input: [1,2,3]
Output: [1,2] (Of course, [1,3] also correct)
Example 2:
Input: [1,2,4,8]
Output: [ 1,2,4,8]
Topic analysis
Suppose the current maximum number divisible by n subset
if the subset can occur x == All numbers divisible> n + 1
appeared! State transition - so use dp Solution
Process Analysis
Set DP [i] represents the maximum number of position i divisible subset
max marking the maximum number of the subset
max_id number of marker subsets maximum starting
parent [i] on a position of the mark is divisible i
- First of nums from small to large
(nums [i] <nums [ j] ==> nums [j] be nums [i] is divisible, then it is divisible by nums [i] is able divisible nums [j])- traversing from 0 i
j i from traversing
if the nums [j] be the nums [i] divisible ==> DP [j] DP = [i] +. 1
parent [i] = j - recording the image of position i a divisible j- If mx <dp [j]
to update and mx mx_id- Finally, according to the answer mx join
code show as below:
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> dp(nums.size(), 0), parent(nums.size(), 0), res;
int mx = 0, mx_idx = 0;
for (int i = nums.size() - 1; i >= 0; --i) {
for (int j = i; j < nums.size(); ++j) {
if (nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
parent[i] = j;
if (mx < dp[i]) {
mx = dp[i];
mx_idx = i;
}
}
}
}
for (int i = 0; i < mx; ++i) {
res.push_back(nums[mx_idx]);
mx_idx = parent[mx_idx];
}
return res;
}
};