# Subsets Leetcode Solution

## SubsetsLeetcode Problem :

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.

## Subsets Leetcode Problem Solution :

### Constraints :

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

### Example:

• Input: nums = [0]
• Output: [[],[0]]

### Idea to solve:

• This is a very common problem in backtracking which is known by Take it or Leave it.
• All we need to do is to create all possible sets, so for each node we will stand over it, we will have two main choices, one to create a set with that node, and the other is to create a set without this node, so after we finsh we will find that we have created all possible unique sets.

### Approach:

The solution depends on two main functions:

backTracking (res, nums, i, sz, sent)
parameters and return type

1. This is a void function, which return nothing.
2. It is a recursive one.
3. res is the result matrix, we sent it by reference to store the sets in it.
4. nums, is the given integer list.
5. i which is the current index.
6. sz, the size of the nums, but I sent it to not get the size in each call.
7. sentr: it is a vector in which we insert the elements, till we reach the base case, then we insert the whole vector at the last case.

### Base Case:

if the current index == size of the nums, then we have exceeded the array, and passed over all elements, so we just need to insert the sentr vector in the result matrix.

### Recursive Logic:

• Insert the nums[i] in the sentr vector.
• Call the backtracking function, and in each call, send i + 1.
• After coming back, pop that element.
• Call the backtracking function again.

### Complexity:

• Time complexity: O(N)
• Space complexity: O(N)

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription