主页 > 人工智能  > 

Python小白的LeetcodeDailyChallenge刷题计划-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!

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()

标签:

Python小白的LeetcodeDailyChallenge刷题计划-20240209(除夕)由讯客互联人工智能栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Python小白的LeetcodeDailyChallenge刷题计划-20240209(除夕)