【leetcode题目整理】数组中找子集

368. Largest Divisible Subset

题意:找到所有元素都不同的数组中满足以下规则的最大子集,规则为:子集中的任意两个元素a和b,满足a%b=0或者b%a=0。

解答:利用动态规划法求解。先给数组排好序。定义dp[i]表示以nums[i]结尾的子集的大小,则dp[i+1]=dp[j]+1,if nums[i+1]%nums[j]==0, 0<=j<=i,或者dp[i+1]=1。时间复杂度为O(n2)。

代码如下:

 1 public List<Integer> largestDivisibleSubset(int[] nums) {
 2         Arrays.sort(nums);
 3         int n = nums.length;
 4         List<Integer> res = new ArrayList<>();
 5         if(n==0) return res;
 6         int[] dp = new int[n];
 7         int[] trace = new int[n];
 8         Arrays.fill(dp, 1);
 9         trace[0]=-1;
10         int max=0, maxIndex=0;
11         for(int i=1; i<n; i++){
12             for(int j=0; j<i; j++){
13                 if(nums[i]%nums[j]==0){
14                     if(dp[i]<dp[j]+1){
15                         dp[i]=dp[j]+1;
16                         trace[i]=j;
17                     }
18                 }
19             }
20             if(dp[i]>max)
21             {
22                 maxIndex=i;
23                 max=dp[i];
24             }
25         }
26 //        print(dp);
27 //        System.out.println();
28 //        print(trace);
29 //        System.out.println();
30         //res.insert(0, nums[maxIndex]);
31         while(maxIndex>=0 && dp[maxIndex]>1){
32             res.add(0, nums[maxIndex]);
33             maxIndex=trace[maxIndex];
34         }
35         res.add(0, nums[maxIndex]);
36         return res;
37     }

 

转载于:https://www.cnblogs.com/shizhh/p/5692978.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值