1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/cpp/largest-divisble-subset.cpp
Matej Focko 54667ca465
cpp: add «368. Largest Divisible Subset»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-02-10 00:18:45 +01:00

61 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;
}