[LeetCode]Largest Divisible Subset | NoobSky
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:
1 | nums: [1,2,3] |
Example 2:
1 | nums: [1,2,4,8] |
这道题的DP思想跟LIS(最长递增子序列)的思想是一样的,详见Longest Increasing Subsequence,只是LIS只要求长度,这里要给出序列。
dp[n]表示最大元素为nums[n]的largest divisible subset的长度,则:
dp[i] = max{dp[j] + 1 if dp[i] % dp[j] == 0}, 0<= j < i
有了以上状态方程,我们可以写出O(n2)的算法。
Read full article from [LeetCode]Largest Divisible Subset | NoobSky
No comments:
Post a Comment