13 lines Java DP solution


  • 0
    W
    public List<Integer> largestDivisibleSubset(int[] nums) {
        List<Integer> result = new ArrayList<>();
        if (nums == null || nums.length == 0) return result;
        Arrays.sort(nums);
        int[] count = new int[nums.length], parents = new int[nums.length];
        int maxIdx = 0;
        for (int i = 0, j; i < nums.length; maxIdx = count[i] > count[maxIdx] ? i : maxIdx, i++)
            for (j = 0, count[i] = 1, parents[i] = -1; j < i; j++)
                if (nums[i] % nums[j] == 0 && count[j] + 1 > count[i]) {
                    count[i] = count[j] + 1;
                    parents[i] = j;
                }
        for (; maxIdx != -1; maxIdx = parents[maxIdx]) result.add(nums[maxIdx]);
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.