标签:
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]
class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { int n = nums.length; List<Integer> res = new ArrayList<>(); if (n == 0) return res; //maxCount keeps maximum length of a subset that has nums[i] as the largest int[] maxCount = new int[n]; //linkToPrev provides a link to previous number in the DivisibleSubset int[] linkToPrev = new int[n]; Arrays.sort(nums); int maxInd = 0; for (int i = 0; i < n; ++i) { maxCount[i] = 1; //include itself in the subset linkToPrev[i] = -1; //-1 indicates a stop for (int divisor = i - 1; divisor >= 0; --divisor) { //iterate backward to see which divisors can be included if (nums[i] % nums[divisor] == 0) { int includeDivisor = maxCount[divisor] + 1; if (includeDivisor > maxCount[i]) { maxCount[i] = includeDivisor; linkToPrev[i] = divisor; } } } if (maxCount[i] > maxCount[maxInd]) { maxInd = i; } } while (maxInd != -1) { res.add(nums[maxInd]); maxInd = linkToPrev[maxInd]; } return res; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5702154.html