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[i] 表示从0到i的最大的可整除子集,那么怎么推出dp[i+1]呢,
从i到0之间,找出第一个k(其中k属于[0,i] )满足nums[i+1]%nums[k]==0,那么有dp[i+1]=dp[k]+1,假使找不到这样的k满足以上等式,那么说明nums[i+1]只能整除自己,所以dp[i+1]=1,找到这样的k后,需要记录下k
题目中要返回最大的长度的可整除子集中某一个最大的,要回溯,所以用一个数组pre来记录,pre[i] 表示的是以i结尾的最大可整除子集中,i的前面一个数的索引index是多少,也就是前面所提到的k。并用一个curMax来记录下遍历过程中最大的dp[i],也就是当前最大的长度,以及对应长度的子集的最后一个元素的索引idx。
举个例子:
pre数组元素初始化元素为-1
例