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}
- 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 ]
]
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);
}
'✘✘✘ Algorithm + Data structure' 카테고리의 다른 글
Prime Number:: 소수 찾기 코드 javascript (0) | 2023.04.09 |
---|---|
[Quick Sort] Quick Select (0) | 2023.01.07 |
[Counting sort] 계수정렬 (0) | 2023.01.01 |
시작: 어차피 한 번은 끝장을 봐야 한다 (0) | 2022.07.02 |
댓글