368. Largest Divisible Subset

题目链接:https://leetcode.com/problems...

dp记录最大的长度,加parent指针存路径。
dp方程是:dp[i] = max(dp[j]) + 1, if nums[i]%nums[j] == 0

public class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        if(nums.length == 0) return new ArrayList();
        int n = nums.length;
        Arrays.sort(nums);
        // dp[i]: largest length of subset include i
        int[] dp = new int[n];
        dp[0] = 1;
        // parent point
        int[] parent = new int[n];
        Arrays.fill(parent, -1);
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < i; j++) {
                if(nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
                    dp[i] = dp[j] + 1;
                    parent[i] = j;
                }
            }
        }
        
        int max = 0, point = 0;
        for(int i = 0; i < n; i++) {
            if(dp[i] > max) {
                max = dp[i];  point = i;
            }
        }
        List<Integer> res = new ArrayList();
        while(point != -1) {
            res.add(nums[point]);
            point = parent[point];
        }
        return res;
    }
}

lulouch13
13 声望6 粉丝