【LeetCode】368. Largest Divisible Subset

﹏ヽ暗。殇╰゛Y 2022-04-18 03:35 271阅读 0赞

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:

  1. Input: [1,2,3]
  2. Output: [1,2] (of course, [1,3] will also be ok)

Example 2:

  1. Input: [1,2,4,8]
  2. Output: [1,2,4,8]

题解

题目大意是求出数组中最长的整除子集,如果将数组排序的话,就是求出来的就是一个等比数列。
所有我们第一步要做的就是给数组排序,这题需要用到动态规划:

动态规划:
对于排序后的数组,第i个位置的数,肯定是【0,i】区间内最大的数,所以我们求【0,i】区间内的最长的整除子集,如果【0,i+1】最长的整除子集大于【0,i】我们就取【0,i+1】,否则我们什么也不干,当然我们还需要用一个数组prePos记录下第i个位置前一个属于整除子集索引,因为数组先要排序,我们需要有个数组来记录原数组的下标索引,方便在搜索结束后,去原数组中寻找对应的数据。

代码

  1. public List<Integer> largestDivisibleSubset(int[] nums) {
  2. List<Integer> ret = new ArrayList<>();
  3. if (nums.length == 0) {
  4. return ret;
  5. }
  6. Arrays.sort(nums);
  7. //记录以i为结尾的最长序列
  8. int[] iLength = new int[nums.length];
  9. //记录当前i,上一个符合最大整除规则的位置
  10. int[] prePos = new int[nums.length];
  11. for (int i = 0; i < nums.length; i++) {
  12. iLength[i] = 1;
  13. //默认情况下,如果prePos不存在,那么自身就是prePost,因为整除子集就一个,是自己本身
  14. prePos[i] = i;
  15. for (int j = 0; j < i; j++) {
  16. //先是判断是否符合规则,再判断是否能够增长,增长即更新结果集否则不更新因为【1,2,3】 [1,2][1,3]都符合,增长没意义
  17. if (nums[i] % nums[j] == 0 && iLength[i] < iLength[j] + 1) {
  18. iLength[i] = iLength[j] + 1;
  19. prePos[i] = j;
  20. }
  21. }
  22. }
  23. //这里先找到最大值,及已最大值的索引
  24. int max = 0;
  25. int maxIndex = 0;
  26. for (int i = 0; i < nums.length; i++) {
  27. if (iLength[i] > max) {
  28. max = iLength[i];
  29. maxIndex = i;
  30. }
  31. }
  32. ret.add(nums[maxIndex]);
  33. //找到最大值后由于prePos数组的特性,我们直接迭代寻找,类似链表一样,尾部链表的prev指向上一个符合整除子集的索引,然后再从原数组取出即可
  34. while (maxIndex != prePos[maxIndex]) {
  35. maxIndex = prePos[maxIndex];
  36. ret.add(nums[maxIndex]);
  37. }
  38. return ret;
  39. }

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读