본문 바로가기
✘✘✘ Algorithm + Data structure

[subset] find all subsets

by PrettyLog 2022. 12. 25.

Number of Subsets of a given Set:

If a set contains ‘n’ elements, then the number of subsets of the set is 2n.

Number of Proper Subsets of the Set:

If a set contains ‘n’ elements, then the number of proper subsets of the set is 2n - 1.

| If A = {p, q} the proper subsets of A are [{ }, {p}, {q}

  1. with loop
const nums = [1, 2, 3];

const subsets = [[]];
function findSubsets(subsets, nums, currentSet, index) {
    if (index > nums.length) {
        return;
    }

    for (let i = index; i < arr.length; i++) {
    const currentValue = nums[i];
    const nextSet = [...currSet, currentValue];
    ans.push(nextSet);
    findSubSets(ans, nums, nextSet, i + 1);
  }

}

console.log(subsets);
---------- Test Case 1 ----------
[
  [],             [ 1 ],
  [ 1, 2 ],       [ 1, 2, 3 ],
  [ 1, 2, 3, 4 ], [ 1, 2, 4 ],
  [ 1, 3 ],       [ 1, 3, 4 ],
  [ 1, 4 ],       [ 2 ],
  [ 2, 3 ],       [ 2, 3, 4 ],
  [ 2, 4 ],       [ 3 ],
  [ 3, 4 ],       [ 4 ]
]
  1. Backtracking to find all subsets
const nums = [1, 2, 3];

const subsets = [];
function findSubsets(subsets, nums, currentSet, index) {
    if (index >= nums.length) {
        subsets.push(currentSet);
        return;
    }

    // store current
    findSubsets(subsets, nums, [...currentSet], index + 1);

    // add current index value
    currentSet.push(nums[index]);
    findSubsets(subsets, nums, [...currentSet], index + 1);
}

댓글