78. Subsets

truongductri01

truongductri01

Posted on June 13, 2023

78. Subsets

Problem Source: 78. Subsets

We will start utilizing UMPIRE method

1. Understand the problem
We want to generate a list containing all the subsets of a given list nums.

2. Matching
This problem seems like generating combinations. We can achieve this by utilizing either BFS or DFS algorithm.
And since we establish a larger subset from the smaller ones, we can use Queue to keep track of that.

3. Plan
We want to create an algorithm which can keep adding the elements and create new subset but maintain the order of elements.

For example, if nums = [1,2,3]. The first subset is obviously [].

Starting with [], we can create 3 new subsets: [1], [2], and [3] by adding 1, 2, and 3 into the empty subset to create new ones.

With this, as long as we know which element did the last subset ends with, we can start appending numbers starting from that index to create new subsets.

Here is the algorithm:

  1. Using recursion
  2. At each recursion, we will keep track of (1) the current subset and (2) the index that subset ends with (the index we can start appending element)
  3. Add the current subset into the resulting list. Then repeat the recursion as long as the index is within the limit of the num arrays

4. Implement

class Solution {
    /**
    Utilize recursion / DFS to construct

    Keep track of result List

    each element still need to be able to know what to do next, right?
    */
    private List<List<Integer>> result;
    public void recursion(List<Integer> root, int[] nums, int idx) {
        result.add(root);

        for (int i = idx; i < nums.length; i++) {
            List<Integer> newList = new ArrayList<>(root);
            newList.add(nums[i]);
            recursion(newList, nums, i + 1);
        }
    }
    public List<List<Integer>> subsets(int[] nums) {
        result = new ArrayList<>();
        List<Integer> empty = new ArrayList<>();

        recursion(empty, nums, 0);

        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Review and Evaluate
This algorithm we generate all possible subsets of a list. If a list is of length n, we will have 2^n.

So this problem will not be good to solve in general if the length of the list grows too large

💖 💪 🙅 🚩
truongductri01
truongductri01

Posted on June 13, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Leetcode Solution #6
coding Leetcode Solution #6

September 16, 2024

729. My Calendar I|| Leetcode || Medium
leetcode 729. My Calendar I|| Leetcode || Medium

September 27, 2024

2024-04-02: Prompt optimizations
devjournal 2024-04-02: Prompt optimizations

April 2, 2024

Learning DSA after 4 years of experience
beginners Learning DSA after 4 years of experience

January 17, 2024