首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode368. Largest Divisible Subset

leetcode368. Largest Divisible Subset

作者头像
眯眯眼的猫头鹰
发布2019-03-13 16:48:28
4300
发布2019-03-13 16:48:28
举报

题目要求

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:

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

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

假设有一组值唯一的正整数数组,找到元素最多的一个子数组,这个子数组中的任选两个元素都可以构成Si % Sj = 0 或 Sj % Si = 0。

思路和代码

这题最核心的思路在于,假如知道前面k个数字所能够组成的满足题意的最长子数组,我们就可以知道第k+1个数字所能构成的最长子数组。只要这个数字是前面数字的倍数,则构成的数组的长度则是之前数字构成最长子数组加一。

这里我们使用了两个临时数组count和pre,分别用来记录到第k个位置上的数字为止能够构成的最长子数组,以及该子数组的前一个可以被整除的值下标为多少。

    public List<Integer> largestDivisibleSubset(int[] nums) {
        int[] count = new int[nums.length];
        int[] pre = new int[nums.length];
        Arrays.sort(nums);
        int maxIndex = -1;
        int max = 0;
        for(int i = 0 ; i<nums.length ; i++) {
            count[i] = 1;
            pre[i] = -1;
            for(int j = i-1 ; j>=0 ; j--) {
                if(nums[i] % nums[j] == 0 && count[j] >= count[i]){
                    count[i] = count[j] + 1;
                    pre[i] = j;
                }
            }
            if(count[i] > max) {
                max = count[i];
                maxIndex = i;
            }
        }
        
        List<Integer> result = new ArrayList<Integer>();
        while(maxIndex != -1){
            result.add(nums[maxIndex]);
            maxIndex = pre[maxIndex];
        }
        return result;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-12-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档