LeetCode 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]
分析
动态规划,首先这题的意思是找出一个子集合,该集合里的任意一对数是可以整除的关系,创建数组dp,dp[i]表示一个子数组以nums[i]结尾时的最大元素个数,可以先把数据按从小到大排序,那么只需要判断dp[i]%dp[j]是否为0了,如果dp[i]%dp[j]==0, dp[i]=max(dp[i],dp[j]+1).否则dp[i]=1. 这题还要记录路径,因为返回的时一个子集合,在每次更新dp[i]时同时让route[i]指向前驱元素,最后在创建一个集合,按route中的路径返回收集元素。
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
if(nums.size()<=1) return nums;
sort(nums.begin(),nums.end());
vector<int> dp(nums.size(),1), route(nums.size(),-1), res;
int index=0,Max=0;
for(int i=1;i<nums.size();i++)
for(int j=i-1;j>=0;j--){
if(nums[i]%nums[j]==0&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
route[i]=j;
if(dp[i]>Max){
Max=dp[i];
index=i;
}
}
}
while(index!=-1){
res.insert(res.begin(),nums[index]);
index=route[index];
}
return res;
}
};