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()
相关推荐
测试19985 小时前
Selenium无法定位元素的几种解决方案详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
大大。5 小时前
Vue3 与 Vue2 区别
前端·面试·职场和发展
兔兔爱学习兔兔爱学习5 小时前
创建Workforce
人工智能·算法
2301_794461576 小时前
力扣-有效三角形的个数
数据结构·算法·leetcode
Tiny番茄6 小时前
LeetCode 39. 组合总和 LeetCode 40.组合总和II LeetCode 131.分割回文串
算法·leetcode·职场和发展
zhangpz_6 小时前
【数据结构】树状数组
数据结构·算法·树状数组
悲伤小伞6 小时前
C++_数据结构_哈希表(hash)实现
数据结构·c++·笔记·算法·哈希算法·散列表
贺函不是涵6 小时前
【沉浸式求职学习day46】【华为5.7暑期机试题目讲解】
学习·算法·华为
June`6 小时前
FloodFill算法:洪水般的图像处理艺术
算法·深度优先
珂朵莉MM7 小时前
2023 睿抗机器人开发者大赛CAIP-编程技能赛-本科组(国赛) 解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论