leetcode - 368. Largest Divisible Subset

文章描述了一种算法,使用动态规划解决一个给定一组不重复正整数的问题,目标是找到最长的子集,使得任意两个元素之间存在整除关系。通过维护以每个数结尾的最长子集长度,找到了求解该问题的有效方法。时间复杂度为O(n^2),空间复杂度为O(n)。
摘要由CSDN通过智能技术生成

Description

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

answer[i] % answer[j] == 0, or
answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

Example 1:

Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.

Example 2:

Input: nums = [1,2,4,8]
Output: [1,2,4,8]

Constraints:

1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 10^9
All the integers in nums are unique.

Solution

Solved after help…

Use dp[i] to keep track of the length of longest subset that ends with nums[i], then the transformation equation is:
d p [ i ] = 1 + max ⁡ ( d p [ j ] ) , ∀    n u m s [ i ] % n u m s [ j ] = = 0 dp[i] = 1 + \max(dp[j]), \forall \;nums[i] \% nums[j] == 0 dp[i]=1+max(dp[j]),nums[i]%nums[j]==0

Because we need to return the longest subset, so when updating the dp, we add another dimension to remember j that we finally choose.

Time complexity: o ( n 2 ) o(n^2) o(n2)
Space complexity: o ( n ) o(n) o(n)

Code

class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        dp = [[1, i] for i in range(len(nums))]
        nums.sort()
        for i in range(1, len(nums)):
            for j in range(i):
                if nums[i] % nums[j] == 0:
                    if dp[j][0] + 1 > dp[i][0]:
                        dp[i][0] = dp[j][0] + 1
                        dp[i][1] = j
        max_len = 1
        res = [nums[dp[0][1]]]
        for i in range(len(dp)):
            if dp[i][0] > max_len:
                res = []
                max_len = dp[i][0]
                index = dp[i][1]
                start_i = i
                while index != start_i:
                    res.append(nums[start_i])
                    start_i = index
                    index = dp[start_i][1]
                res.append(nums[start_i])
        return res
  • 22
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值