leetcode368. Largest Divisible Subset

来源:互联网 发布:淘宝网.女士运动鞋. 编辑:程序博客网 时间:2024/05/29 18:55

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3]
Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8]
Result: [1,2,4,8]

简单的dp
dp[i]=dp[j]+[nums[i]]
其中设置一些条件即可

class Solution(object):    def largestDivisibleSubset(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        if nums==[]:            return nums        nums.sort()        dp=[[0] for i in range(len(nums))]        for i in range(len(nums)):            idx=-1            length=-1            for j in range(i):                if (nums[i]%nums[j]==0 or nums[j]%nums[i]==0) and (len(dp[j])>=length):                    length=len(dp[j])                    idx=j             if idx!=-1:                dp[i]=dp[idx]+[nums[i]]            if dp[i]==[0]:                dp[i]=[nums[i]]        return max(dp,key=lambda x:len(x))
0 0
原创粉丝点击