Python 小白的 Leetcode Daily Challenge 刷题计划 - 20240209(除夕)

368. Largest Divisible Subset

难度:Medium

  • 动态规划 + 方案还原

Yesterday's Daily Challenge can be reduced to the problem of shortest path in an unweighted graph while today's daily challenge can be reduced to the problem of longest path in an unweighted graph.

Happy Chinese New Year!

python 复制代码
class Solution:
    def largestDivisibleSubset(self, nums: list[int]) -> list[int]:
        n = len(nums)
        nums.sort()
        f, pre = [1]*n, [-1]*n
        t = 0
        for i in range(n):
            for j in range(i):
                if nums[i] % nums[j] == 0:
                    if f[j]+1 > f[i]:
                        f[i] = f[j]+1
                        pre[i] = j
                if f[i] > f[t]:
                    t = i
        ans = []
        while t != -1:
            ans.append(nums[t])
            t = pre[t]
        return ans

def test():
    samples = [[1,2,3],
               [1,2,4,8]]
    sol = Solution()
    for nums in samples:
        print(sol.largestDivisibleSubset(nums))

if __name__ == '__main__':
    test()
相关推荐
汉克老师3 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
Mr_Xuhhh4 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
c++bug4 小时前
六级第一关——下楼梯
算法
Morri34 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
林木辛4 小时前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
AndrewHZ5 小时前
【3D算法技术】blender中,在曲面上如何进行贴图?
算法·3d·blender·贴图·三维建模·三维重建·pcg
Jared_devin5 小时前
二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值
数据结构·c++·算法·职场和发展·蓝桥杯
AI 嗯啦6 小时前
数据结构深度解析:二叉树的基本原理
数据结构·算法
和光同尘@7 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_027 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode