|
| 1 | +# 🧠 [Subsets](https://leetcode.com/problems/subsets/description/) |
| 2 | + |
| 3 | +## 💡 Intuition |
| 4 | + |
| 5 | +To generate all possible subsets (the power set) of an array of unique integers, we recognize that each element has two |
| 6 | +choices: either it is included in a subset or it is not. This binary decision at each element leads to a total of |
| 7 | +\(2^n\) subsets for an array of length \(n\). |
| 8 | + |
| 9 | +The key idea is to simulate this decision-making process iteratively using a queue (Breadth-First Search style), where |
| 10 | +each tuple in the queue represents a current subset and the index of the element being considered next. |
| 11 | + |
| 12 | +## 🔍 Approach |
| 13 | + |
| 14 | +- Use a `Deque` to perform a breadth-first construction of subsets. |
| 15 | +- Begin with an empty subset and index 0. |
| 16 | +- While the number of generated subsets is less than \(2^n\), pop a tuple off the queue. |
| 17 | +- For each tuple, branch into two new tuples: |
| 18 | + - One that keeps the subset as is (excluding the current index). |
| 19 | + - One that includes the current index element in the subset. |
| 20 | +- Push both new tuples back into the queue with the index incremented. |
| 21 | +- Continue until all subsets are generated. |
| 22 | +- Return only the subsets (not the indices). |
| 23 | + |
| 24 | +## ⏱️ Complexity |
| 25 | + |
| 26 | +- **Time Complexity**: \(O(2^n \cdot n)\) |
| 27 | + - There are \(2^n\) subsets. |
| 28 | + - Each subset can take up to \(O(n)\) time to copy or create. |
| 29 | +- **Space Complexity**: \(O(2^n \cdot n)\) |
| 30 | + - Due to storing all subsets in memory. |
| 31 | + |
| 32 | +## 🧪 Code |
| 33 | + |
| 34 | +- [Java](../src/main/java/io/dksifoua/leetcode/subsets/Solution.java) |
| 35 | + |
| 36 | +## ✅ Summary |
| 37 | + |
| 38 | +This solution takes an iterative BFS-inspired approach to subset generation. It systematically expands each subset by |
| 39 | +including or excluding the current element. The result is an efficient and clean method that produces all \(2^n\) |
| 40 | +subsets without duplication. |
0 commit comments