# 40. Combination Sum II

Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.

Each number in `candidates` may only be used **once** in the combination.

**Note:** The solution set must not contain duplicate combinations.

```java
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res =  new ArrayList<>();
        Arrays.sort(candidates);
        dfs(candidates, target, res, new ArrayList<>(), 0);
        return res;   
    }
    
    private void dfs(int[] candidates, int target, List<List<Integer>> res, List<Integer> ans, int start){
        if (target == 0){
            res.add(new ArrayList<>(ans));
        }
        if (target<=0) return;
        
        for (int i=start; i<candidates.length; i++){
            // i>start to make sure duplicated number is allowed in different depth
            // candidates[i]==candidates[i-1] avoid duplication in same depth
            if (i>start && candidates[i]==candidates[i-1]) continue;
            ans.add(candidates[i]);
            dfs(candidates, target-candidates[i], res, ans, i+1);
            ans.remove(ans.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://ucan.gitbook.io/notes/backtrack/40.-combination-sum-ii.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.
