~/DHRUVUpskilling
← board/DSA/Subsets/dsa-subsets-01
Solved·28 Sept

Subsets

DifficultyMedium
PatternSubsets
TrackDSA
tl;dr

return all the combination of subsets

full write-up

Statement Given an array of integers, nums, find all possible subsets of nums, including the empty set.

Note: The solution set must not contain duplicate subsets. You can return the solution in any order.

Constraints:

1 ≤ 1≤ nums.length ≤ 10 ≤10 − 10 ≤ −10≤ nums[i] ≤ 10 ≤10 All the numbers of nums are unique.

Solution

To find total number of subsets we'll use binary representation of numbers. we'll start a loop from zero that will goes to 2^n. Now we'll check at which position we have 1 so one loop to get binary number and one for finding 1 in that loop. once we find a number we'll add that index number to subset


function getbit(num, k) {

    let temp = 1 << k;
    temp = temp & num;

    if (temp == 0) {
        return 0
    }

    return 1;
}

var subsets = function (nums) {
    let totalCombination = Math.pow(2, nums.length);
    let set = []

    for (let i = 0; i < totalCombination; i++) {

        let subset = new Set();

        for (let j = 0; j < nums.length; j++) {

            if (getbit(i, j) && !subset.has(nums[j])) {

                subset.add(nums[j])
            }

        }

        set.push(Array.from(subset));
    }

    return set;
};

Subsets — pattern notes — Dhruv Parmar