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()
相关推荐
油泼辣子多加5 小时前
【DL】Transformer算法应用
人工智能·深度学习·算法·机器学习·transformer
2301_795741795 小时前
C++中的代理模式变体
开发语言·c++·算法
fof9205 小时前
Base LLM | 从 NLP 到 LLM 的算法全栈教程 第二天
人工智能·算法·自然语言处理
2301_789015625 小时前
封装RBTree(红黑树)实现myset和mymap
开发语言·数据结构·c++·算法·r-tree
大鹏说大话5 小时前
后端开发指南:同步与异步接口的选型策略与实战场景
算法
Book思议-5 小时前
【数据结构实战】双向链表:删除节点
c语言·数据结构·算法·链表
y = xⁿ5 小时前
【LeetCodehot100】 T543:二叉树的直径 T102:二叉树的层序遍历
算法
敲上瘾5 小时前
位图与布隆过滤器:原理、实现与海量数据处理方案
大数据·数据结构·算法·位图·布隆过滤器
宵时待雨5 小时前
C++笔记归纳13:map & set
开发语言·数据结构·c++·笔记·算法
1104.北光c°6 小时前
滑动窗口HotKey探测机制:让你的缓存TTL更智能
java·开发语言·笔记·程序人生·算法·滑动窗口·hotkey