Teaching Kids Programming – Finding All Subsets by Bitmasking Algorithm


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:
Input: nums = [0]
Output: [[],[0]]

Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.

Finding All Subsets by Bitmasking Algorithm

Given N unique numbers, the total number of subsets is tex_7da98591b3d78eeec743ae932ec8bcb8 Teaching Kids Programming - Finding All Subsets by Bitmasking Algorithm algorithms bit hacks math python teaching kids programming youtube video . Thus, w can iterate the number from 0 to tex_1159ac3b784acae00551ffa7f78650f7 Teaching Kids Programming - Finding All Subsets by Bitmasking Algorithm algorithms bit hacks math python teaching kids programming youtube video and each number (in binary) corresponds to a selection of numbers in the current subset. For example:

0 – 000 – []
1 – 001 – [1]
2 – 010 – [2]
3 – 011 – [1, 2]
4 – 100 – [3]
5 – 101 – [1, 3]
6 – 110 – [2, 3]
7 – 111 – [1, 1, 1]

For each binary number, we have to loop over each number/index to see if that bit is set – if yes include it in the current subset.

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def subsets(self, nums: list[int]) -> list[int]:
        n = len(nums)
        ans = []        
        for i in range(1 << n):
            cur = []
            for j in range(n):
                if i & (1 << j):
                    cur.append(nums[j])
            ans.append(cur)
        return ans   
class Solution:
    def subsets(self, nums: list[int]) -> list[int]:
        n = len(nums)
        ans = []        
        for i in range(1 << n):
            cur = []
            for j in range(n):
                if i & (1 << j):
                    cur.append(nums[j])
            ans.append(cur)
        return ans   

The time complexity is O(N*2^N)

Subsets Algorithms

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
508 words
Last Post: Teaching Kids Programming - Finding All Subsets via Backtracking Algorithm (Recursion / Depth First Search)
Next Post: Teaching Kids Programming - Cascading Algorithm to Find All Subsets

The Permanent URL is: Teaching Kids Programming – Finding All Subsets by Bitmasking Algorithm

Leave a Reply