Subsets LeetCode Solution

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

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

Subsets Leetcode Solution C++

class Solution {
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> cache;
        vector<int> temp;
        subsets(nums, cache, temp, 0);
        return cache;
    void subsets(vector<int>& nums, vector<vector<int>>& cache, vector<int> &temp, int start) {
        if(start == nums.size()) {
        subsets(nums, cache, temp, start + 1);
        subsets(nums, cache, temp, start + 1);
};Code language: PHP (php)

Subsets Leetcode Solution Java

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> list = new ArrayList<>();
    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++){
        backtrack(list, tempList, nums, i + 1);
        tempList.remove(tempList.size() - 1);        
}Code language: PHP (php)

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    
};Code language: JavaScript (javascript)

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