> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/40.-combination-sum-ii.md).

# 40. Combination Sum II

## 1.問題

![](/files/-LO8K17fC0IxE3UFn8BE)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 時間複雜度與可用空間是否有限制?&#x20;
  * member是否可以重複使用?
  * 重複的排列是否視為同一個?
* function header, parameter
* test input
* 說明想法
  * 這個問題有點類似39 Combination sum, 但允許member被重複使用
  * 加入限制條件, 當candidates\[i] == candidates\[i - 1]時continue
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> record;
        vector<bool> used(candidates.size(), false);
        sort(candidates.begin(), candidates.end());
        getCombinationSum(res, record, candidates, used, target, 0);
        return res;
    }
private:
    void getCombinationSum(vector<vector<int>>& res, vector<int>& record, vector<int>& candidates, vector<bool>& used, int target, int start) {
        if (target < 0) {
            return;
        }
        
        if (target == 0) {
            res.push_back(record);
            return;
        }
        
        for (int i = start; i < candidates.size(); i++) {
            if (i > start && candidates[i] == candidates[i - 1]){
                continue;
            }
            record.push_back(candidates[i]);
            getCombinationSum(res, record, candidates, used, target - candidates[i], i + 1);
            record.pop_back();
        }
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://jenhsuan.gitbook.io/algorithm/leetcode/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.
