Subsets LeetCode Solution

Last updated on October 9th, 2024 at 10:42 pm

Here, We see Subsets LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Array, Backtracking, Bit-Manipulation

Companies

Amazon, Bloomberg, Facebook, Uber

Level of Question

Medium

Subsets LeetCode Solution

Subsets LeetCode Solution

Problem Statement

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]]

1. Subsets Leetcode Solution C++

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> cache;
        vector<int> temp;
        subsets(nums, cache, temp, 0);
        return cache;
    }
private:
    void subsets(vector<int>& nums, vector<vector<int>>& cache, vector<int> &temp, int start) {
        if(start == nums.size()) {
            cache.push_back(temp);
            return;
        }
        temp.push_back(nums[start]);
        subsets(nums, cache, temp, start + 1);
        temp.pop_back();
        subsets(nums, cache, temp, start + 1);
        }      
};

2. Subsets Leetcode Solution Java

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, 0);
    return list;
}

private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){
    list.add(new ArrayList<>(tempList));
    for(int i = start; i < nums.length; i++){
        tempList.add(nums[i]);
        backtrack(list, tempList, nums, i + 1);
        tempList.remove(tempList.size() - 1);        
    }
}
}

3. Subsets Leetcode Solution JavaScript

var subsets = function(nums) {
	let res=[]                    // the final arr, which we will display
	let auxArr = [], i=0             // global vars
    function recur(nums,i,auxArr){
        if(i==nums.length) { res.push(auxArr); return } 
        recur(nums, i+1, [...auxArr, nums[i] ] ) //or, we can use 'aux.concat(nums[i])'
        recur(nums, i+1, auxArr) 
    }  
    recur(nums,i,auxArr) // passing the global variable declared already
    return res    
};

4. Subsets Leetcode Solution Python

class Solution(object):
    def subsets(self, nums):
        res = [[]]
        for n in nums:
            for i in range(len(res)):
                res.append(res[i] + [n])
        return res
Scroll to Top