368. Largest Divisible Subset
题目描述: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]
题目大意:给定一个数组,找出数组中任意两个数可以相整除的最大子序列的长度。
思路:
- 排序
- 找到最大子序列的长度
- 记录最大子序列的最后一个元素
- 从后向前遍历添加属于最大子序列中的元素
- dp[i]表示0到i位置处的最大可整除子序列的长度
代码
package DP; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author OovEver * 2018/1/4 23:23 */ public class LeetCode416 { public List<Integer> largestDivisibleSubset(int[] nums) { List<Integer> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } Arrays.sort(nums); int []dp=new int[nums.length]; Arrays.fill(dp, 1); // dp[i]表示0到i中最大的可整除子序列中元素的个数 for (int i=1;i<nums.length;i++) { for(int j=i-1;j>=0;j--) { if (nums[i] % nums[j] == 0) { dp[i] = Math.max(dp[i], dp[j] + 1); } } } int maxIndex = 0; for(int i=1;i<nums.length;i++) { if (dp[i] > dp[maxIndex]) { maxIndex = i; } } int temp = nums[maxIndex]; int curDp = dp[maxIndex]; for(int i=maxIndex;i>=0;i--) { if (temp%nums[i]==0 && curDp == dp[i]) { res.add(nums[i]); temp = nums[i]; curDp--; } } return res; } }