# 78. Subsets

### Description

Given a set of **distinct** integers, *nums*, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

### **Constraints**

### **Approach**

### Links

* GeeksforGeeks
* [Leetcode](https://leetcode.com/problems/subsets)
* ProgramCreek
* YouTube

### Examples

{% tabs %}
{% tab title="Example 1" %}
**Input:** nums = \[1, 2, 3]

**Output:** \[ \[], \[1], \[2], \[3], \[1, 2], \[1, 3], \[2, 3], \[1, 2, 3] ]
{% endtab %}
{% endtabs %}

### Solutions

{% tabs %}
{% tab title="Solution 1" %}

```java
/**
 * Time complexity : O(N×2^N) to generate all subsets and then copy 
 *    them into output list.
 * Space complexity : O(N×2^N) to keep all the subsets of length N, 
 *    since each of N elements could be present or absent.
 */

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> resultList = new ArrayList<>();
        for(int k = 0; k <= nums.length; k++) {
            backtrack(resultList, new LinkedList<Integer>(), nums, 0, k);
        }
        return resultList;
    }
    private void backtrack(
        List<List<Integer>> resultList,
        LinkedList<Integer> currList,
        int[] nums,
        int start,
        int k
    ) {
        if(k == 0) {
            resultList.add(new ArrayList(currList));
        }
        for(int i = start; i < nums.length; i++) {
            currList.add(nums[i]);
            backtrack(resultList, currList, nums, i+1, k-1);
            currList.removeLast();
        }
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code-snippets.hbamithkumara.com/leetcode/problems/1-100/subsets.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
