题目描述:
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]这个题我的思路是先排序,每次记下来第nums[i]能形成的最大的list,办法是创建NumMultiple来保存nums[i]和nums[i对应的List,]从后往前找nums[i]的最小因子,找得到就直接加入nums[i],找不到则nums[i]重新组成list
例如8,3,6,4,2,9这个序列,先排序成2,3,4,6,8,9
1、先让2单独形成list
2、3前面没有自己的因子,所以3单独组成list
3、4是2的倍数,所以2、4组成list
4、6是3的倍数,所以3、6组成list
5、8是4的倍数,所以2、4、8组成list
6、9是3的倍数,所以3、9组成list
2:[2]
3:[3]
4:[2, 4]
6:[3, 6]
8:[2, 4, 8]
9:[3, 9]
[2, 4, 8]
代码如下:(这里我重写了toString方法,方便理解代码,看的更清晰)
public class Solution { class NumMultiple{ int num; List<Integer> list; public NumMultiple(int num,List<Integer> list){ this.num=num; this.list=list; } @Override public String toString() { // TODO Auto-generated method stub return num+":"+list; } } public List<Integer> largestDivisibleSubset(int[] nums) { int n=nums.length; List<Integer> result=new ArrayList<Integer>(); if(n==0) return result; Arrays.sort(nums); List<NumMultiple> list=new ArrayList<NumMultiple>(); List<Integer> l=new ArrayList<Integer>(); l.add(nums[0]); NumMultiple numMultiple=new NumMultiple(nums[0], l); list.add(numMultiple); System.out.println(numMultiple); looper:for(int i=1;i<n;i++){ for(int j=list.size()-1;j>=0;j--){ if(nums[i]%list.get(j).num==0){ List<Integer> newList=new ArrayList<Integer>(list.get(j).list); newList.add(nums[i]); list.add(new NumMultiple(nums[i], newList)); System.out.println(new NumMultiple(nums[i], newList)); continue looper; } } List<Integer> newList=new ArrayList<Integer>(); newList.add(nums[i]); list.add(new NumMultiple(nums[i], newList)); System.out.println(new NumMultiple(nums[i], newList)); } int maxIndex=0,maxLength=0; for(int i=0;i<list.size();i++){ if(list.get(i).list.size()>maxLength){ maxIndex=i; maxLength=list.get(i).list.size(); } } return list.get(maxIndex).list; } }