【leetcode】368. Largest Divisible Subset【M】【65】
2016-07-04 15:11
387 查看
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:
Example 2:
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
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
相关文章推荐
- Hibernate的sessionFactory的封装
- [置顶] mfc怎么动态加载时间以及改变字体大小和颜色。
- CSS3中Animation动画属性用法详解
- use AP_VENDOR_PUB_PKG.Update_Vendor_Site_Public to u ORA-01722: invalid number in Package AP_VENDOR_PUB_PKG Procedure Update_Vendor_Site_Public
- 虚拟机上rad hat网络相关设置
- Android 设计模式 笔记 - Builder模式
- MyBatis学习总结(四)解决字段名与实体类属性名不相同的冲突
- 正则表达式
- VxWorks网络协议栈的MUX接口
- cocoscreator中使用canvas模式
- 线性时间排序 计数排序(Counting Sort)
- 利用Python实现归并排序
- Linux下的系统性能调优工具——Perf
- Yii控制器中操作视图js的方法
- JavaScript强化教程——jQuery动画
- linux "-bash: telnet: command not found" telnet不是命令
- 关于更换fc adaper的几个小问题
- dubbo启动报错 java.net.UnknownHostException: bogon: bogon: Name or service not known
- CentOS7 安装 tensorflow 0.8
- javap反编译解释外部类直接使用内部类private字段的原理