mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
cpp: add «368. Largest Divisible Subset»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
b562aea45e
commit
54667ca465
1 changed files with 61 additions and 0 deletions
61
cpp/largest-divisble-subset.cpp
Normal file
61
cpp/largest-divisble-subset.cpp
Normal file
|
@ -0,0 +1,61 @@
|
|||
#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;
|
||||
}
|
Loading…
Reference in a new issue