반응형
https://leetcode.com/problems/largest-divisible-subset
class Solution {
public:
vector<int> res, temp;
int dp[1001] = {0};
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(), nums.end());
dfs(nums, 0, 1);
return res;
}
void dfs(vector<int>& nums, int idx, int prv) {
if(idx == nums.size()) {
if(res.size() < temp.size()) res = temp;
return;
}
int r = nums.size() - idx;
if(temp.size() + r < res.size()) {
return;
}
dfs(nums, idx + 1, prv);
if (dp[idx] <= (int)temp.size() && nums[idx] % prv == 0) {
temp.push_back(nums[idx]);
dp[idx] = temp.size();
dfs(nums, idx + 1, nums[idx]);
temp.pop_back();
}
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 169. Majority Element (0) | 2024.02.13 |
---|---|
LeetCode 1463. Cherry Pickup II (0) | 2024.02.12 |
LeetCode 279. Perfect Squares (0) | 2024.02.08 |
LeetCode 451. Sort Characters By Frequency (0) | 2024.02.07 |
LeetCode 1457. Pseudo-Palindromic Paths in a Binary Tree (0) | 2024.01.25 |