368. Largest Divisible Subset

本文介绍了一种解决LeetCode 368题——寻找给定数组中最大整除子集的方法。通过先对数组进行排序,然后使用动态规划算法找到满足条件的最大子集,并详细解释了实现过程。

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]
  • 题目大意:给定一个数组,找出数组中任意两个数可以相整除的最大子序列的长度。

  • 思路:

    1. 排序
    2. 找到最大子序列的长度
    3. 记录最大子序列的最后一个元素
    4. 从后向前遍历添加属于最大子序列中的元素
    5. dp[i]表示0到i位置处的最大可整除子序列的长度
  • 代码

    package DP;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    /**
    * @author OovEver
    * 2018/1/4 23:23
    */
    public class LeetCode416 {
      public List<Integer> largestDivisibleSubset(int[] nums) {
          List<Integer> res = new ArrayList<>();
          if (nums == null || nums.length == 0) {
              return res;
          }
          Arrays.sort(nums);
          int []dp=new int[nums.length];
          Arrays.fill(dp, 1);
    //        dp[i]表示0到i中最大的可整除子序列中元素的个数
          for (int i=1;i<nums.length;i++) {
              for(int j=i-1;j>=0;j--) {
                  if (nums[i] % nums[j] == 0) {
                      dp[i] = Math.max(dp[i], dp[j] + 1);
                  }
              }
          }
          int maxIndex = 0;
          for(int i=1;i<nums.length;i++) {
              if (dp[i] > dp[maxIndex]) {
                  maxIndex = i;
              }
          }
          int temp = nums[maxIndex];
          int curDp = dp[maxIndex];
          for(int i=maxIndex;i>=0;i--) {
              if (temp%nums[i]==0 && curDp == dp[i]) {
                  res.add(nums[i]);
                  temp = nums[i];
                  curDp--;
              }
          }
          return res;
      }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值