LeetcodeLargest Divisible Subset

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeLargest Divisible Subset相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/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]

思路:
dp
dp数组表示从0~i包括第i个元素最大的divisible subset size
pre数组用来标记 状态转移过程中的方向,用于回溯最大值时的解集。
dp[i]=max{dp[i],dp[j]+1}

算法:

    public List<Integer> largestDivisibleSubset(int[] nums) {
        LinkedList<Integer> res = new LinkedList<Integer>();
        if (nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);

        int dp[] = new int[nums.length]; //记录从0~i包括nums[i]的最大subset的size
        int pre[] = new int[nums.length];//记录到当前元素最大size的前一位数的下标
        int maxIdx = -1, max = -1;

        for (int i = 0; i < nums.length; i++) { //初始化
            dp[i] = 1;
            pre[i] = -1;
        }

        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) {
                    dp[i] = dp[j] + 1;
                    pre[i] = j;// 
                }
            }
        }

        for (int i = 0; i < nums.length; i++) {//找到最大的子集size 和它最后元素的下标
            if (dp[i] > max) {
                max = dp[i];
                maxIdx = i;
            }
        }

        for (int i = maxIdx; i >= 0;) { //回溯解集
            res.addFirst(nums[i]);
            i = pre[i];
        }
        return res;
    }

以上是关于LeetcodeLargest Divisible Subset的主要内容,如果未能解决你的问题,请参考以下文章

Largest Divisible Subset

LightOJ1125 Divisible Group Sums

368. Largest Divisible Subset

Leetcode: Largest Divisible Subset

Largest Divisible Subset -- LeetCode

[LintCode] Largest Divisible Subset