# 39. Combination Sum 组合总和

@TOC

## # 题目描述

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]
]
``````

## # 解题方法

### # 方法一：递归

Python代码如下：

``````class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
self.dfs(candidates, target, 0, res, [])
return res

def dfs(self, nums, target, index, res, path):
if target < 0:
return
elif target == 0:
res.append(path)
return
for i in xrange(index, len(nums)):
if nums[index] > target:
return
self.dfs(nums, target - nums[i], i, res, path + [nums[i]])
``````

### # 方法二：回溯法

C++代码如下：

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

## # 日期

2018 年 2 月 13 日 2018 年 12 月 19 日 —— 感冒了，好难受 2019 年 9 月 25 日 —— 做梦都在秋招，这个秋天有毒