# 39. Combination Sum

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/combination-sum/

> 内容描述

```
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

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

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

```

## 解题方案

> 思路 1
******- 时间复杂度: O(2^n)******- 空间复杂度: O(2^n)******

此题可以用递归拆分为子问题求解。
每一个子问题（步），有两种情况需要考虑：
1. 跳过当前数字
2. 取当前数字并继续保留当前数字为 candidates


失败条件是 candidates 为空或 target 为负 或 idx >= len(cadidates)

beats 48.49%

```python
class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def helper(remain, combi, idx):
            if remain < 0:
                return 
            if remain == 0:
                res.append(combi)
                return
            if idx >= len(candidates):
                return
            helper(remain, combi, idx+1)
            helper(remain-candidates[idx], combi+[candidates[idx]], idx)
        
        res = []
        helper(target, [], 0)
        return res
```
