368. Largest Divisible Subset

Question

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]


Code

public class Solution {
    public class Data {
        public int index;
        public int count;
        public int pre;
        
        public Data(int index, int count, int pre) {
            this.index = index;
            this.count = count;
            this.pre = pre;
        }
    }
    
    public List largestDivisibleSubset(int[] nums) {
        List result = new ArrayList<>();
        if (nums == null || nums.length == 0) return result;
        if (nums.length == 1) {
            result.add(nums[0]);
            return result;
        }
        
        Arrays.sort(nums);
        
        Data[] dp = new Data[nums.length];
        dp[0] = new Data(0, 1, 0);
        int max = 1;
        Data record = dp[0];
        
        for (int i = 1; i < dp.length; i++) {
            dp[i] = new Data(i, 1, i);
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    if (dp[j].count + 1 > dp[i].count) {
                        dp[i].count = dp[j].count + 1;
                        dp[i].pre = j;
                    }
                    if (dp[i].count > max) {
                            max = dp[i].count;
                            record = dp[i];
                    }
                }
            }
        }
        
        while (record.index != record.pre) {
            result.add(0, nums[record.index]);
            record = dp[record.pre];
        }
        result.add(0, nums[record.index]);
        return result;
    }
}

Solution

动态规划实现。

实现了一个内部类,类中包含三个元素:index表示该元素在nums中的下标,count表示含有nums[index]的最大可除子序列的长度,pre表示该序列的前一个元素在nums中的下标。初始化时,pre = index, count = 1.

对于nums中的每一个元素nums[i],遍历其之前的nums[j],当nums[i] % nums[j] == 0时,使用状态转移方程:dp[i].count = Math.max(dp[i].count, dp[j].count + 1)。同时更新dp[i].pre = j。在遍历nums[i]的过程中,用int max记录最大的count,用Data record记录拥有最大count的Data。

遍历完成后,通过record.pre不断回溯,将所有的num添加到结果集中。

你可能感兴趣的:(368. Largest Divisible Subset)