62 lines
1.4 KiB
C++
62 lines
1.4 KiB
C++
|
#include <algorithm>
|
||
|
#include <cassert>
|
||
|
#include <vector>
|
||
|
|
||
|
struct Solution {
|
||
|
std::vector<int> largestDivisibleSubset(std::vector<int> nums) {
|
||
|
std::sort(nums.begin(), nums.end());
|
||
|
|
||
|
solver s(nums);
|
||
|
s.solve();
|
||
|
return s.result;
|
||
|
}
|
||
|
|
||
|
private:
|
||
|
struct solver {
|
||
|
const std::vector<int> &nums;
|
||
|
int n;
|
||
|
std::vector<std::size_t> dp;
|
||
|
std::vector<int> tmp;
|
||
|
std::vector<int> result;
|
||
|
|
||
|
solver(const std::vector<int> &nums)
|
||
|
: nums(nums), n(nums.size()), dp(nums.size() + 1, 0) {}
|
||
|
|
||
|
void solve() { solve(0); }
|
||
|
|
||
|
void solve(int i) {
|
||
|
if (i >= n) {
|
||
|
if (tmp.size() > result.size()) {
|
||
|
result = tmp;
|
||
|
}
|
||
|
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
if (tmp.empty() ||
|
||
|
(tmp.size() > dp[i] && nums[i] % tmp.back() == 0)) {
|
||
|
dp[i] = std::max(dp[i], tmp.size());
|
||
|
|
||
|
tmp.push_back(nums[i]);
|
||
|
solve(i + 1);
|
||
|
tmp.pop_back();
|
||
|
}
|
||
|
|
||
|
solve(i + 1);
|
||
|
}
|
||
|
};
|
||
|
};
|
||
|
|
||
|
int main() {
|
||
|
Solution s;
|
||
|
|
||
|
assert(
|
||
|
(s.largestDivisibleSubset(std::vector{1, 2, 3}) == std::vector{1, 2}));
|
||
|
assert((s.largestDivisibleSubset(std::vector{1, 2, 4, 8}) ==
|
||
|
std::vector{1, 2, 4, 8}));
|
||
|
assert((s.largestDivisibleSubset(std::vector{3, 4, 16, 8}) ==
|
||
|
std::vector{4, 8, 16}));
|
||
|
|
||
|
return 0;
|
||
|
}
|