1. 程式人生 > >Largest Divisible Subset_LeetCode

Largest Divisible Subset_LeetCode

ret eve this 排序 The 是否 multipl example bsp

#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