2024-05-23 Daily Challenge
Today I have done leetcode's May LeetCoding Challenge with cpp.
May LeetCoding Challenge 23
Description
The Number of Beautiful Subsets
You are given an array nums of positive integers and a positive integer k.
A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.
Return the number of non-empty beautiful subsets of the array nums.
A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [2,4,6], k = 2 Output: 4 Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6]. It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
Example 2:
Input: nums = [1], k = 1 Output: 1 Explanation: The beautiful subset of the array nums is [1]. It can be proved that there is only 1 beautiful subset in the array [1].
Constraints:
1 <= nums.length <= 201 <= nums[i], k <= 1000
Solution
class Solution {
vector<int> visit = vector<int>(1001);
bool isBeautiful(vector<int>& nums, int k, int subset) {
bool ok = true;
for(int i = 0; i < nums.size() && ok; ++i) {
if(!((1 << i) & subset)) continue;
if(nums[i] > k && visit[nums[i] - k]) ok = false;
if(nums[i] + k < 1001 && visit[nums[i] + k]) ok = false;
visit[nums[i]] = true;
}
for(int i = 0; i < nums.size(); ++i) {
if(!((1 << i) & subset)) continue;
visit[nums[i]] = false;
}
return ok;
}
public:
int beautifulSubsets(vector<int>& nums, int k) {
int allCombinations = (1 << nums.size());
if(isBeautiful(nums, k, allCombinations - 1)) return allCombinations - 1;
int answer = 0;
for(int i = 1; i < allCombinations; ++i) {
answer += isBeautiful(nums, k, i);
}
return answer;
}
};