国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

368. Largest Divisible Subset -Medium

2019-11-11 07:08:27
字體:
來源:轉載
供稿:網友

Question

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.

給出一個不重復的正整數集合,找出滿足 Si % Sj = 0 或者 Sj % Si = 0 的最長可整除子序列。如果有多個解,只需返回任意一個即可

Example

nums: [1,2,3]

Result: [1,2] (of course, [1,3] will also be ok)


nums: [1,2,4,8]

Result: [1,2,4,8]

Solution

動態規劃解。這道題和LIS非常相似,LIS的要求是遞增,而最長可正整除序列的要求則是可整除。所以只要我們先將列表排序,這樣只需判斷 Si % Sj = 0 (i > j),再接下來就和LIS完全一樣了(和我上一篇差不多就不寫了)。不過這里需要輸出一種結果。所以我們還需要額外保存每個元素的上一個元素索引。

class Solution(object): def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ if len(nums) == 0: return [] # 先排序保證只需要相除一次 nums.sort() dp = [1] * len(nums) dp_index = [-1] * len(nums) # 保存元素的上一個元素的索引,用于得到序列 max_len = 1 # 維護一個最長子序列的長度 for index_n, n in enumerate(nums): for i in range(index_n): if n % nums[i] == 0 and dp[i] + 1 > dp[index_n]: dp[index_n] = dp[i] + 1 dp_index[index_n] = i # 每次更新dp時同時保存其上一個元素的索引 max_len = max(dp[i] + 1, max_len) result = [] # 定位到第一個最長子序列的結尾 index = dp.index(max_len) # 根據dp_index反向保存最長子序列 while index != -1: result.append(nums[index]) index = dp_index[index] # 得到上一個元素的索引 result.reverse() # 倒序 return result
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 梨树县| 东莞市| 宁海县| 涟水县| 宜春市| 庄河市| 兴海县| 茂名市| 西盟| 多伦县| 当涂县| 宜宾市| 阿城市| 交口县| 垦利县| 谷城县| 莱西市| 闵行区| 吴堡县| 陇西县| 沅江市| 郑州市| 万州区| 枝江市| 茶陵县| 乌鲁木齐县| 景宁| 临颍县| 长治市| 菏泽市| 宝丰县| 昌邑市| 山东| 米泉市| 南城县| 宁波市| 陆良县| 石家庄市| 兖州市| 顺平县| 万载县|