美文网首页Leetcode
Leetcode 368. Largest Divisible

Leetcode 368. Largest Divisible

作者: SnailTyan | 来源:发表于2021-02-09 09:49 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Largest Divisible Subset

    2. Solution

    • Version 1
    class Solution:
        def largestDivisibleSubset(self, nums):
            nums.sort()
            length = len(nums)
            dp = [1] * length
            for i in range(length):
                for j in range(i + 1, length):
                    if nums[j] % nums[i] == 0:
                        dp[j] = max(dp[j], dp[i] + 1)
    
            max_index = dp.index(max(dp))
            result = [nums[max_index]]
            for i in range(max_index - 1, -1 , -1):
                if nums[max_index] % nums[i] == 0 and dp[i] == dp[max_index] - len(result) and result[-1] % nums[i] == 0:
                    result.append(nums[i])
    
            result.reverse()
            return result
    

    Reference

    1. https://leetcode.com/problems/largest-divisible-subset/

    相关文章

      网友评论

        本文标题:Leetcode 368. Largest Divisible

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