📅  最后修改于: 2023-12-03 15:11:09.277000             🧑  作者: Mango
给定一个整数数组 nums,找到其中所有通过以下条件构造出的最大子集:
示例 1: 输入: nums = [1,2,3] 输出: [1,2] (当然,[1,3] 也是可能的)
思路1:动态规划
思路2:贪心
思路1:动态规划
思路2:贪心
思路1:动态规划
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
n = len(nums)
if n <= 1:
return nums
nums.sort()
dp = [1]*n
max_len = 1
index = 0
for i in range(1, n):
for j in range(i):
if nums[i] % nums[j] == 0:
dp[i] = max(dp[i], dp[j]+1)
if dp[i] > max_len:
max_len = dp[i]
index = i
result = []
t = nums[index]
for i in range(index, -1, -1):
if t % nums[i] == 0 and dp[i] == max_len:
result.append(nums[i])
t = nums[i]
max_len -= 1
return result
思路2:贪心
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
n = len(nums)
if n <= 1:
return nums
nums.sort()
result = []
max_len = 0
for i in range(n):
temp = []
for j in range(max_len):
if nums[i] % result[j] == 0:
temp.append(result[j])
temp.append(nums[i])
result = temp
max_len = max(max_len, len(result))
return result