LeetCode 368. Largest Divisible Subset

原题链接在这里:https://leetcode.com/problems/largest-divisible-subset/description/

题目:

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

Example 1:

nums: [1,2,3]

Result: [1,2] (of course, [1,3] will also be ok)

Example 2:

nums: [1,2,4,8]

Result: [1,2,4,8]

题解:

 求最长的subset, subset中每两个数大的除以小的余数是0. 储存到当前点, 包括当前点, 符合要求的最大subset长度.

Let count[i] denotes largest subset ending with i.

For all j < i, if nums[i] % nums[j] == 0, then i could be added after j and may construct a largeer subset. Update count[i]. 

But how to get the routine. Use preIndex[i] denotes the pre index of i in the largest subset. Then could start with last index and get pre num one by one. 

Time Complexity: O(n^2). n = nums.length.

Space: O(n).

AC Java:

复制代码
 1 class Solution {
 2     public List<Integer> largestDivisibleSubset(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         
 5         if(nums == null || nums.length == 0){
 6             return res;    
 7         }
 8         
 9         int len = nums.length;
10         Arrays.sort(nums);
11         int [] count = new int[len];
12         int [] preIndex = new int[len];
13         int resCount = 0;
14         int resIndex = -1;
15         
16         for(int i = 0; i<len; i++){
17             count[i] = 1;
18             preIndex[i] = -1;
19             for(int j = 0; j<i; j++){
20                if(nums[i]%nums[j] == 0 && count[j]+1 > count[i]){
21                    count[i] = count[j]+1;
22                    preIndex[i] = j;
23                } 
24             }
25             
26             if(resCount < count[i]){
27                 resCount = count[i];
28                 resIndex = i;
29             }
30         }
31         
32         while(resIndex != -1){
33             res.add(0, nums[resIndex]);
34             resIndex = preIndex[resIndex];
35         }
36         
37         return res;
38     }
39 }
复制代码

类似Longest Increasing Subsequence

posted @   Dylan_Java_NYC  阅读(252)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示