【LeetCode】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:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:
Input: [1,2,4,8]
Output: [1,2,4,8]
题解
题目大意是求出数组中最长的整除子集,如果将数组排序的话,就是求出来的就是一个等比数列。
所有我们第一步要做的就是给数组排序,这题需要用到动态规划:
动态规划:
对于排序后的数组,第i
个位置的数,肯定是【0,i】区间内最大的数,所以我们求【0,i】区间内的最长的整除子集,如果【0,i+1】最长的整除子集大于【0,i】我们就取【0,i+1】,否则我们什么也不干,当然我们还需要用一个数组prePos
记录下第i
个位置前一个属于整除子集索引,因为数组先要排序,我们需要有个数组来记录原数组的下标索引,方便在搜索结束后,去原数组中寻找对应的数据。
代码
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> ret = new ArrayList<>();
if (nums.length == 0) {
return ret;
}
Arrays.sort(nums);
//记录以i为结尾的最长序列
int[] iLength = new int[nums.length];
//记录当前i,上一个符合最大整除规则的位置
int[] prePos = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
iLength[i] = 1;
//默认情况下,如果prePos不存在,那么自身就是prePost,因为整除子集就一个,是自己本身
prePos[i] = i;
for (int j = 0; j < i; j++) {
//先是判断是否符合规则,再判断是否能够增长,增长即更新结果集否则不更新因为【1,2,3】 [1,2][1,3]都符合,增长没意义
if (nums[i] % nums[j] == 0 && iLength[i] < iLength[j] + 1) {
iLength[i] = iLength[j] + 1;
prePos[i] = j;
}
}
}
//这里先找到最大值,及已最大值的索引
int max = 0;
int maxIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (iLength[i] > max) {
max = iLength[i];
maxIndex = i;
}
}
ret.add(nums[maxIndex]);
//找到最大值后由于prePos数组的特性,我们直接迭代寻找,类似链表一样,尾部链表的prev指向上一个符合整除子集的索引,然后再从原数组取出即可
while (maxIndex != prePos[maxIndex]) {
maxIndex = prePos[maxIndex];
ret.add(nums[maxIndex]);
}
return ret;
}
还没有评论,来说两句吧...