【leetcode】368. Largest Divisible Subset【M】【65】
来源:互联网 发布:php 环境 代码 编辑:程序博客网 时间:2024/05/22 00:05
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]
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
动态规划
首先对数组进行排序,这样保证小的在前面
地推公式是
dp[i] = max{dp[j] + t[j]}, j < i
t[j] = 1, if nums[i] %nums[j]
0 ,else
然后使用ind数组,记录数组
ind[i] = j, if dp[j] is the max
class Solution(object): def largestDivisibleSubset(self, nums): if nums == []: return [] nums.sort() # print nums dp = [1] * len(nums) ind = [-1] * len(nums) for i in xrange(len(nums)): t = 1 for j in xrange(i): if nums[i] % nums[j] == 0 and dp[j] + 1 >= t: t = dp[j]+1 ind[i] = j dp[i] = t maxx = max(dp) i = dp.index(maxx)#len(nums) - 1 res = [] while i >= 0: res += nums[ind[i]], i = ind[i] return res
0 0
- 【leetcode】368. Largest Divisible Subset【M】【65】
- [leetcode] 368. Largest Divisible Subset
- Leetcode 368. Largest Divisible Subset
- LeetCode 368. Largest Divisible Subset
- leetcode 368. Largest Divisible Subset
- [leetcode] 368. Largest Divisible Subset
- leetcode.368. Largest Divisible Subset
- [Leetcode]368. Largest Divisible Subset
- [leetcode] 368. Largest Divisible Subset
- leetcode 368. Largest Divisible Subset
- [leetcode] 368. Largest Divisible Subset
- [leetcode] 368. Largest Divisible Subset
- Leetcode: 368. Largest Divisible Subset
- *Leetcode 368. Largest Divisible Subset
- Leetcode-368. Largest Divisible Subset
- Leetcode 368. Largest Divisible Subset
- Leetcode 368. Largest Divisible Subset
- LeetCode 368. Largest Divisible Subset
- Hibernate的sessionFactory的封装
- mfc怎么动态加载时间以及改变字体大小和颜色。
- android bluedroid 协议栈里面的各个组件之间的消息处理机制
- Redis-sentinel哨兵模式集群方案配置
- No More findViewById
- 【leetcode】368. Largest Divisible Subset【M】【65】
- JAVA调用SAP端RFC接口
- opencv给视频添加文字_ cvPutText使用说明
- #define定义函数
- Android测试工具收集
- CSS选择器
- SQL设置SQLServer最大连接数
- Servlet系统配置
- Activity context And Application context