https://leetcode.com/problems/largest-divisible-subset/description/
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]
首先对数组排序,这里我按照升序排列。
创建两个数组,n和pos,n[i]代表nums[i]在其所在子数组中的位置,pos[i[代表其下一个除数的在nums中的位置,即nums[pos[i]]%nums[i] == 0。
然后遍历数组。在遍历的过程中吗,每到一个元素都再次遍历先前遍历过的部分,如果存在当前遍历元素的因数,则判断n[i] < n[j]+1,是否成立。因为这可以判断nums[j]是否是nums[i]最近的一个因数, 如果是,才会进入下一步。
n[i] = n[j]+1;意味着i是j在子数组中的后一位。
pos[i] = j,这样只要知道子数组最后一个元素在nums中的的位置,就可以知道子数组所有元素的位置。
最大子数组的最后一个元素位置用maxpos记录,max为最大子数组长度。
遍历完成后,我已经得知最大子数组的长度以及最大子数组最后一位在nums中的位置。
通过
for (int i = max; i > 0; i--) {
m.push_back(nums[maxpos]);
maxpos = pos[maxpos];
}
不断的向前读取,直到将最大子数组所有元素全部存入m中,返回m。
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
if (!nums.size()) return vector<int>();
sort(nums.begin(), nums.end());
int pos[nums.size()] = {0}, n[nums.size()] = {0};
int max = 0, maxpos = 0;
for (int i = 0; i < nums.size(); i++) {
for (int j = i; j >= 0; j--) {
if (0 == nums[i]%nums[j]&& n[i] < 1 + n[j]) {
n[i] = n[j]+1;
pos[i] = j;
if (n[i] > max) {
max = n[i];
maxpos = i;
}
}
}
}
vector<int> m;
for (int i = max; i > 0; i--) {
m.push_back(nums[maxpos]);
maxpos = pos[maxpos];
}
return m;
}
};
40 / 40 test cases passed.
Status: Accepted
Runtime: 32 ms
本文提供了一种解决LeetCode上最大整除子集问题的有效算法。通过对输入数组进行排序,并使用动态规划的方法,寻找出满足条件的最大子集。最终实现了32毫秒运行时间的解决方案。
391

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



