Teaching Kids Programming – Cascading Algorithm to Find All Subsets


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.

Cascading Algorithm to Find All Subsets

The idea of cascading is to iterate over the numbers and append each to the existing subsets as the new subsets. Therefore at each iteration, the size of subsets doubles. For example: consider [1,2,3].

ans = [[]]
take number 1: make a copy of all subsets [[]], and append 1 to them to make new subsets e.g. [1].
take number 2: make a copy of all subsets [[],[1]] and append 2 to them to make new subsets e.g. [2],[1,2]
take number 3: make a copy of all subsets [[],[1],[2],[1,2]] and append 3 to them which makes: [3],[1,3],[2,3],[1,2,3]

The following Python code implements the cascading algorithm to find all subsets given a list that consists of unique numbers. Both time and space complexity is tex_927f1f18f03846bde511ae269f07007b Teaching Kids Programming - Cascading Algorithm to Find All Subsets algorithms math python teaching kids programming youtube video .

1
2
3
4
5
6
7
class Solution:
    def subsets(self, nums: list[int]) -> list[int]:        
        n = len(nums)
        ans = [[]]        
        for n in nums:
            ans += [c + [n] for c in ans]            
        return ans
class Solution:
    def subsets(self, nums: list[int]) -> list[int]:        
        n = len(nums)
        ans = [[]]        
        for n in nums:
            ans += [c + [n] for c in ans]            
        return ans

Subsets Algorithms

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
509 words
Last Post: Teaching Kids Programming - Finding All Subsets by Bitmasking Algorithm
Next Post: Teaching Kids Programming - Permutation of K out of N Visible Blocks via Top Down Dynamic Programming Algorithm

The Permanent URL is: Teaching Kids Programming – Cascading Algorithm to Find All Subsets

Leave a Reply