# Subset

\[A general backtracking template]\(<https://leetcode.com/problems/subsets/discuss/27281/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partitioning>)

## 78 Subset

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

* Time O(2^n)

```java
public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(nums);
    dfs(nums, 0, new ArrayList<>(), result);
    return result;
}

private void dfs(int[] nums, int index, List<Integer> subset, List<List<Integer>> result){
    result.add(new ArrayList(subset));
    for(int i = index; i < nums.length; i++){
        subset.add(nums[i]);
        dfs(nums, i + 1, subset, result);
        subset.remove(subset.size()-1);
    } 
}
```

## 90 Subset ll

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set)duplicate number in list

* Add duplicate condition

```java
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] nums) {
    ArrayList<ArrayList<Integer>> result = new ArrayList<>();
    Arrays.sort(nums);
    subsetsHelper(nums, new ArrayList(), 0, result);
    return result;
}

private void subsetsHelper(int[] nums,
                            ArrayList<Integer> subset,
                            int index,
                            ArrayList<ArrayList<Integer>> result){

    result.add(new ArrayList(subset));
    for(int i = index; i < nums.length; i++){
        if(i > index && nums[i] == nums[i-1]){ // 只使用第一個duplicate
            continue;    
        }
        subset.add(nums[i]);
        subsetsHelper(nums, subset, i + 1, result); //不是index+1
        subset.remove(subset.size()-1);
    }
}
```


---

# 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://netjimmy.gitbook.io/code-interview-note/dfs/set.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.
