# 39. Combination Sum

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LO8J0YG1SLWJ3IkQz2Q%2F-LO8JjuP2DjVn8qA_dGe%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-06%20%E4%B8%8B%E5%8D%888.20.02.png?alt=media\&token=cd86f8ad-342b-4b4a-85ee-8dbe3f567218)

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

* 提問
  * 時間複雜度與可用空間是否有限制?&#x20;
  * member是否可以重複使用?
  * 重複的排列是否視為同一個?
* function header, parameter
* test input
* 說明想法
  * 這個問題有點類似permutation, 但是數條件為總和等於target, 而且允許member被重複使用
  * 因此可以修改permutation的解法, 但是不要記錄member是否被使用過, 並且限制起始點
* 測試計算複雜度

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

```
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> record;
        getCombinationSum(res, record, candidates, target, 0);
        return res;
    }
private:
    void getCombinationSum(vector<vector<int>>& res, vector<int>& record, vector<int>& candidates, int target, int start) {
        if (target < 0) {
            return;
        }
        
        if (target == 0) {
            res.push_back(record);
            return;
        }
        
        for (int i = start; i < candidates.size(); i++) {
            record.push_back(candidates[i]);
            getCombinationSum(res, record, candidates, target - candidates[i], i);
            record.pop_back();
        }
    }
};
```
