zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    第1章 基础知识
    图学习学术速递[2021/10/14]
    图学习学术速递[2021/10/15]
    期望—方差—协方差—协方差矩阵—相关系数
    哈达玛积
    论文解读(MPNN)Neural Message Passing for Quantum Chemistry
    pip 命令总结
    图学习学术速递[2021/10/13]
    Codeforces Round #693 (Div. 3) D. Even-Odd Game
    Codeforces Round #693 (Div. 3) B. Fair Division
  • 原文地址:https://www.cnblogs.com/phinza/p/10301587.html
Copyright © 2011-2022 走看看