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()
相关推荐
weixin_395448918 分钟前
main.c_cursor_0129
前端·网络·算法
CS创新实验室21 分钟前
《计算机网络》深入学:路由算法与路径选择
网络·计算机网络·算法
一条大祥脚21 分钟前
ABC357 基环树dp|懒标记线段树
数据结构·算法·图论
tod11321 分钟前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode
naruto_lnq32 分钟前
C++中的桥接模式
开发语言·c++·算法
苦藤新鸡32 分钟前
50.腐烂的橘子
数据结构·算法
想进个大厂38 分钟前
代码随想录day32 动态规划01
算法·动态规划
j445566111 小时前
C++中的职责链模式高级应用
开发语言·c++·算法
uesowys1 小时前
Apache Spark算法开发指导-Decision tree classifier
算法·决策树·spark
池央1 小时前
贪心算法-最大数
算法·贪心算法