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()
相关推荐
椰羊~王小美40 分钟前
LeetCode -- Flora -- edit 2025-04-27
算法·leetcode·职场和发展
缘友一世2 小时前
从线性回归到逻辑回归
算法·逻辑回归·线性回归
前端_学习之路2 小时前
javaScript--数据结构和算法
javascript·数据结构·算法
迷路的小绅士3 小时前
计算机网络核心知识点全解析(面试通关版)
计算机网络·面试·职场和发展
weixin_428498493 小时前
使用HYPRE库并行装配IJ稀疏矩阵指南: 矩阵预分配和重复利用
算法·矩阵
雾削木5 小时前
mAh 与 Wh:电量单位的深度解析
开发语言·c++·单片机·嵌入式硬件·算法·电脑
__lost5 小时前
小球在摆线上下落的物理过程MATLAB代码
开发语言·算法·matlab
中小企业实战军师刘孙亮5 小时前
实体店的小程序转型之路:拥抱新零售的密码-中小企实战运营和营销工作室博客
职场和发展·小程序·创业创新·学习方法·业界资讯·零售·内容运营
mit6.8246 小时前
[Lc_week] 447 | 155 | Q1 | hash | pair {}调用
算法·leetcode·哈希算法·散列表
jerry6097 小时前
优先队列、堆笔记(算法第四版)
java·笔记·算法