• Largest Divisible Subset_LeetCode


    #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

  • 相关阅读:
    shell-3
    shell-2
    shell-1
    zabbix监控top
    django指导网址
    文件下载漏洞
    Build a Raspberry Pi powered live train station sign for your desk
    Use a Raspberry Pi to communicate with Amazon AWS IoT
    Describing and Listing Your Stacks
    固有功能参考 Intrinsic Function Reference
  • 原文地址:https://www.cnblogs.com/phinza/p/10301587.html
Copyright © 2020-2023  润新知