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; } }