368. 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]

一刷
题解:
先把数组排好序。首先要明确,若a 我们设dp[i] 为最大的子集长度,更新的时候保存上一个的下标即可。

public class Solution {
    public List largestDivisibleSubset(int[] nums) {
        List res = new ArrayList();
        if(nums.length == 0) return res;
        Arrays.sort(nums);
        int n = nums.length;
        int[] dp = new int[n], index = new int[n];
        Arrays.fill(dp, 1);
        Arrays.fill(index, -1);
        int max_index = 0, max_dp = 1;
        for(int i=0; i=0; j--){
                if(nums[i] % nums[j] == 0 && dp[j]+1>dp[i]){
                    dp[i] = dp[j]+1;
                    index[i] = j;
                }
            }
            
            if(max_dp

二刷
同上,但是要记住用index array作为指针(链表)这个特点

class Solution {
    public List largestDivisibleSubset(int[] nums) {
        List res = new ArrayList<>();
        int len = nums.length;
        if(len==0) return res;
        int[] dp = new int[len], index = new int[len];
        int max_len = 1, max_index = 0;
        Arrays.sort(nums);
        Arrays.fill(dp, 1);
        Arrays.fill(index, -1);
        for(int i=0; i=0; j--){
                if(nums[i]%nums[j] == 0 && dp[i]max_len){
                max_len = dp[i];
                max_index = i;
            }
        }
        
        for(int i=max_index; i>=0; i=index[i]){
            res.add(nums[i]);
        }
        return res;
    }
}

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