Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create 2597-the-number-of-beautiful-subsets.js #3780

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions javascript/2597-the-number-of-beautiful-subsets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* BackTracking | Hashing | Recursion
* Time O(2^n * n) | Space O(n)
* https://leetcode.com/problems/the-number-of-beautiful-subsets
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var beautifulSubsets = function(nums, k) {

const numSet = {};

const checkIfValid = (arr) => {
if (!arr.length) return false;
for( let i = 0; i < arr.length; i++) {
const key0 = arr[i] - k;
const key1 = arr[i] + k;

if (numSet[key0]) return false;
if (numSet[key1]) return false;
}
return true;
}

const addToNumSet = (key) => {
numSet[key] = (numSet[key] && numSet[key] + 1) || 1;
}

const removeFromNumSet = (key) => {
numSet[key] -= 1;
}

let result = 0;
const dfs = (arr, i) => {
if (i === nums.length) {
if (checkIfValid(arr)) result++;
return;
}

// we have 2 choices.
arr.push(nums[i]);
addToNumSet(nums[i]);
dfs(arr, i+1);
arr.pop(nums[i]);
removeFromNumSet(nums[i]);
dfs(arr, i+1);
}

dfs([],0);
return result;
};