# 40     Combination Sum II

## 40. [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/description/)

## 1. Question

Given a collection of candidate numbers (**C**) and a target number (**T**), find all unique combinations in **C** where the candidate numbers sums to **T**.

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

**Note:**

* All numbers (including target) will be positive integers.
* The solution set must not contain duplicate combinations.

For example, given candidate set`[10, 1, 2, 7, 6, 1, 5]`and target`8`,\
A solution set is:

```
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
```

## 2. Implementation

**(1) Backtracking**

```java
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> combinations = new ArrayList<>();
        Arrays.sort(candidates);
        getCombinations(candidates, 0, 0, target, combinations, res);
        return res;
    }

    public void getCombinations(int[] candidates, int index, int sum, int target, List<Integer> combinations, List<List<Integer>> res) {
        if (sum > target) {
            return;
        }

        if (sum == target) {
            res.add(new ArrayList<>(combinations));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (i > index && candidates[i - 1] == candidates[i]) {
                continue;
            }

            combinations.add(candidates[i]);
            getCombinations(candidates, i + 1, sum + candidates[i], target, combinations, res);
            combinations.remove(combinations.size() - 1);
        }
    }
}
```

## 3. Time & Space Complexity

**Backtracking**: 时间复杂度O(2^n), 空间复杂度O(2^n)


---

# 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://protegejj.gitbook.io/oj-practices/chapter1/backtracking/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.
