码迷,mamicode.com
首页 > 其他好文 > 详细

Largest Divisible Subset_LeetCode

时间:2019-01-22 00:34:37      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:一个   tin   visible   res   替代   sel   bsp   sort   必须   

#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:

#Input: [1,2,3]
#Output: [1,2] (of course, [1,3] will also be ok)

#Example 2:

#Input: [1,2,4,8]
#Output: [1,2,4,8]

#思路1:A,B,C三个数,如果B能被A整除,C能被B整除,那么C一定能被A整除。
#思路2:建立循环,I不断往前面找可以被整除的数,找到了就添加进组,如果有更长的选择,则替代
class Solution(object):
    def largestDivisibleSubset(self, nums):
        nums.sort() #为了好好比较,必须先排序
        temp = [[nums[i]] for i in range(len(nums))] #建立每个数的数组以便之后添加
        for i in range(1,len(nums)): #循环1号
            for j in range(i-1, -1, -1): #循环2号,起点比1号小一个位置,往回倒着走
                if nums[i] % nums[j] == 0: #检测是否可以整除
                    if len(temp[j]) + 1 > len(temp[i]): #如果有更长的选择,比如[4,8,10,120]中 [4,8]与[10]对于120的选择
                        temp[i] = temp[j] + [nums[i]] #替代

        maxi, res = 0, []
        for i in temp:
            if len(i) > maxi:
                maxi, res = len(i), i
        return res

Largest Divisible Subset_LeetCode

标签:一个   tin   visible   res   替代   sel   bsp   sort   必须   

原文地址:https://www.cnblogs.com/phinza/p/10301587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!