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 小时前
浅谈:算法中的斐波那契数(二)
算法·职场和发展
不穿格子的程序员5 小时前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
liuyao_xianhui6 小时前
寻找峰值--优选算法(二分查找法)
算法
dragoooon346 小时前
[hot100 NO.19~24]
数据结构·算法
Tony_yitao7 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹8 小时前
任务总执行时长
java·数据结构·算法·华为·面试
风筝在晴天搁浅8 小时前
代码随想录 463.岛屿的周长
算法
一个不知名程序员www8 小时前
算法学习入门---priority_queue(C++)
c++·算法
TL滕9 小时前
从0开始学算法——第十八天(分治算法)
笔记·学习·算法