leetcode368. 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:

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;
    }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~this

相关文章
相关标签/搜索