Subsets – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
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.
C++ Subsets LeetCode Solution
Recursive (Backtracking)
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> subs;
vector<int> sub;
subsets(nums, 0, sub, subs);
return subs;
}
private:
void subsets(vector<int>& nums, int i, vector<int>& sub, vector<vector<int>>& subs) {
subs.push_back(sub);
for (int j = i; j < nums.size(); j++) {
sub.push_back(nums[j]);
subsets(nums, j + 1, sub, subs);
sub.pop_back();
}
}
};
Java Subsets LeetCode Solution
public List<List<Integer>> subsets(int[] nums) {
Arrays.sort(nums); // make sure subsets are ordered
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>()); // start with empty set
for (int i = 0; i < nums.length; ++i) {
for (int j = 0, size = result.size(); j < size; ++j) { // remember
List<Integer> subset = new ArrayList<>(result.get(j)); // copy a new one
subset.add(nums[i]); // expand
result.add(subset); // collect
}
}
return result;
}
Python 3 Subsets LeetCode Solution
class Solution(object):
def subsets(self, nums):
nums.sort()
result = [[]]
for num in nums:
result += [i + [num] for i in result]
return result
Array-1180
String-562
Hash Table-412
Dynamic Programming-390
Math-368
Sorting-264
Greedy-257
Depth-First Search-256
Database-215
Breadth-First Search-200
Tree-195
Binary Search-191
Matrix-176
Binary Tree-160
Two Pointers-151
Bit Manipulation-140
Stack-133
Heap (Priority Queue)-117
Design-116
Graph-108
Simulation-103
Prefix Sum-96
Backtracking-92
Counting-86
Sliding Window-73
Linked List-69
Union Find-66
Ordered Set-48
Monotonic Stack-47
Recursion-43
Trie-41
Binary Search Tree-40
Divide and Conquer-40
Enumeration-39
Bitmask-37
Queue-33
Memoization-32
Topological Sort-31
Geometry-30
Segment Tree-27
Game Theory-24
Hash Function-24
Binary Indexed Tree-21
Interactive-18
Data Stream-17
String Matching-17
Rolling Hash-17
Shortest Path-16
Number Theory-16
Combinatorics-15
Randomized-12
Monotonic Queue-9
Iterator-9
Merge Sort-9
Concurrency-9
Doubly-Linked List-8
Brainteaser-8
Probability and Statistics-7
Quickselect-7
Bucket Sort-6
Suffix Array-6
Minimum Spanning Tree-5
Counting Sort-5
Shell-4
Line Sweep-4
Reservoir Sampling-4
Eulerian Circuit-3
Radix Sort-3
Strongly Connected Componen-t2
Rejection Sampling-2
Biconnected Component-1
Leave a comment below