资讯专栏INFORMATION COLUMN

368. Largest Divisible Subset

mmy123456 / 1436人阅读

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 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 res = new ArrayList();
        while(point != -1) {
            res.add(nums[point]);
            point = parent[point];
        }
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69871.html

相关文章

  • Leetcode[368] Largest Divisible Subset

    摘要:让数组从小到大排序。因为如果一个数能被加到这个中的话,说明这个数能被这个中的最大的数整除。同样可以用一个数组来记录之前搜索过的。,表示的是我们搜索的路径是从到。初始化这个位置是头结点。说明是,并没有是当前最大的里的最大值。 LeetCode[368] Largest Divisible Subset Given a set of distinct positive integers,...

    springDevBird 评论0 收藏0
  • 368. Largest Divisible Subset

    摘要:题目解答参考的里的解法,核心思想从小到大,每一位数都能被比他大的数整除。对于从后往前看,找出每一个可以被它整除的数的数组,并更新它作为从这里开始,往后最大的,记录下最大数组开始的地方,并把下一个数记在里找出最长的这个数组中的每一个数 题目:Given a set of distinct positive integers, find the largest subset such th...

    source 评论0 收藏0
  • leetcode368. Largest Divisible Subset

    摘要:题目要求假设有一组值唯一的正整数数组,找到元素最多的一个子数组,这个子数组中的任选两个元素都可以构成或。只要这个数字是前面数字的倍数,则构成的数组的长度则是之前数字构成最长子数组加一。 题目要求 Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj)...

    Honwhy 评论0 收藏0
  • Python基础练习100题 ( 11~ 20)

    摘要:刷题继续上一期和大家分享了前道题,今天继续来刷解法一解法二解法三解法一解法二解法三解法四解法一解法二解法三解法一解法二解法三解法一解法二解法一解法一解法二解法一解法二解法三解法四解法一解法一源代码下载这十道题的 刷题继续 上一期和大家分享了前10道题,今天继续来刷11~20 Question 11: Write a program which accepts a sequence o...

    luckyw 评论0 收藏0
  • [LeetCode/LintCode] Largest Palindrome Product

    Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...

    Barry_Ng 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<