LeetCode 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]

题解:

类似Longest Increasing Subsequence.

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

递推时, 当前点 i 前面每一个点 j 若可以被 i 整除 并且 1+j 点对应的最长subset长度 比现有 i 点对应的最长subset长度长, 就更新 i 点对应的最长subset长度. 同时更新 i 的整除对应关系.

初始化, 最长subset就是当前点. 长度为1.

答案 维护最长subset对应的index, 并通过记录的整除对应关系找回所有点.

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         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         
 8         Arrays.sort(nums);
 9         
10         int len = nums.length;
11         int [] count = new int[len];
12         int [] pre = new int[len];
13         int max = 0;
14         int index = -1;
15         
16         for(int i = 0; i<len; i++){
17             count[i] = 1;
18             pre[i] = -1;
19             
20             for(int j = 0; j<i; j++){
21                 if(nums[i]%nums[j] == 0 && count[i]<count[j]+1){
22                     count[i] = count[j]+1;
23                     pre[i] = j;
24                 }
25             }
26             
27             if(count[i] > max){
28                 max = count[i];
29                 index = i;
30             }
31         }
32         
33         while(index != -1){
34             res.add(nums[index]);
35             index = pre[index];
36         }
37         
38         return res;
39     }
40 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7619919.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值