链接:https://leetcode-cn.com/problems/largest-divisible-subset/
先把数组排个序,维护一个数组,存储以每个元素为结尾的最大集合的元素个数,处理每个元素时,向前遍历即可。
java代码:
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer>res = new ArrayList();
if(nums.length==0)
return res;
int max = 1; //存储目前可以生成的最大的集合的元素个数
int index = 0; //存储目前可以生成的最大集合 中 最大数的 下标
Arrays.sort(nums);
int [] lastIndex = new int [nums.length]; //存储每个元素的 “前一个元素” 的下标
int [] maxSet = new int [nums.length]; //存储以每一个元素为结尾,可以生成的最大的集合的元素个数
maxSet[0] = 1;
lastIndex[0] = -1;
for(int i = 1;i<nums.length;i++)
{
int tempMax = 0;
int tempIndex = -1;
for(int j = i-1;j>=0;j--)
{
if(nums[i]%nums[j]==0&&maxSet[j]>tempMax)
{
tempMax = maxSet[j];
tempIndex = j;
}
}
lastIndex[i] = tempIndex;
maxSet[i] = tempMax+1;
if(tempMax+1>max)
{
max = tempMax+1;
index = i;
}
}
res.add(nums[index]);
while(lastIndex[index]!=-1)
{
index = lastIndex[index];
res.add(nums[index]);
}
return res;
}
}
本文提供了一种解决LeetCode上最大整除子集问题的有效算法。通过先对数组进行排序,然后使用动态规划的方法,维护一个数组来存储以每个元素为结尾的最大集合的元素个数。代码实现采用Java,详细解释了如何向前遍历处理每个元素,找到符合条件的最大子集。
&spm=1001.2101.3001.5002&articleId=105933921&d=1&t=3&u=5b25d0fe1e6348148860630265013b0e)
345

被折叠的 条评论
为什么被折叠?



