美文网首页
368. Largest Divisible Subset

368. Largest Divisible Subset

作者: becauseyou_90cd | 来源:发表于2018-07-26 21:47 被阅读0次

    解题思路:

    1. 用动态规划得到dp[i] represents the largest divisible subset numbers.

    代码:
    class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {

        List<Integer> res = new ArrayList<>();
        if(nums == null || nums.length == 0) return res;
        int len = nums.length;
        int[] dp = new int[len];
        Arrays.fill(dp, 1);
        Arrays.sort(nums);
        for(int i = 1; i < len; i++){
            for(int j = i - 1; j >= 0; j--){
                if(nums[i] % nums[j] == 0){
                    dp[i] = Math.max(dp[i], dp[j]  + 1);
                }
            }
        }
        
        int maxIndex = 0;
        for(int i = 1; i < len; i++){
            maxIndex = dp[i] > dp[maxIndex] ? i : maxIndex;
        }
        
        int temp = nums[maxIndex];
        int curDp = dp[maxIndex];
        for(int i = maxIndex; i >= 0; i--){
            if(temp % nums[i] == 0 && dp[i] == curDp){
                res.add(nums[i]);
                temp = nums[i];
                curDp--;
            }
        }
        return res;
    }
    

    }

    相关文章

      网友评论

          本文标题:368. Largest Divisible Subset

          本文链接:https://www.haomeiwen.com/subject/nbrvmftx.html