DEV Community

Karleb
Karleb

Posted on

#2597. The Number of Beautiful Subsets

https://leetcode.com/problems/the-number-of-beautiful-subsets/?envType=daily-question&envId=2024-05-24

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var beautifulSubsets = function(nums, k) {
    let result = 0

    function backtrack(start, subset) {
        if (subset.length > 0) result++

        for (let i = start; i < nums.length; i++) {
            let valid = true
            for(let num of subset) {
                if (Math.abs(num - nums[i]) === k) {
                    valid = false
                    break
                }
            }

            if (valid) { 
                subset.push(nums[i])
                backtrack(i + 1, subset)
                subset.pop()
            }
        }
    } 

    backtrack(0, [])
    return result
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)