Leetcode 368. Largest Divisible Subset

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 list来保存从一开头到当前这个数字的最长subset的长度,但是由于本题需要返回的是一个list,我们用pre来保存在当前最长subset中上一个元素的位置。

 1 class Solution(object):
 2     def largestDivisibleSubset(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[int]
 6         """
 7         nums.sort()
 8         n = len(nums)
 9         if n == 0:
10             return []
11         elif n ==1:
12             return nums
13         dp = [1]*n
14         pre = [None]*n
15         
16         for i in range(n):
17             for j in range(i):
18                 if nums[i]% nums[j] == 0 and dp[j] +1 > dp[i]:
19                     dp [i] = dp[j] + 1
20                     pre[i] = j
21         
22         idx = dp.index(max(dp))
23         ans = []
24         while idx is not None:
25             ans.append(nums[idx])
26             idx = pre[idx]
27         return ans

 

posted @ 2016-12-03 02:36  lettuan  阅读(170)  评论(0编辑  收藏  举报