# Combination Sum

void dfscombine(vector<int>& candidates,int level,int& sum,int target,vector<int>& mid,vector<vector<int> >& result)
{
if(sum>target) return;
else if(sum==target)
result.push_back(mid);
else
{
for(int i=level;i<candidates.size();i++)
{
sum+=candidates[i];
mid.push_back(candidates[i]);
dfscombine(candidates,i,sum,target,mid,result);
mid.pop_back();
sum-=candidates[i];
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> mid;
vector<vector<int> > result;
sort(candidates.begin(),candidates.end());
int level=0,sum=0;
dfscombine(candidates,level,sum,target,mid,result);
return result;
}

dfscombine(candidates,i,sum,target,mid,result)这一行代码中可以看出，我们每次递归都将candidates[i]$candidates[i]$重复计算，为了保证每个数只出现一次，只需将i$i$该为i+1$i+1$即可，因为collision中会存在相等的数，为了保证结果的唯一性要在for循环最后加入代码：

while(i<candidates.size()-1 && candidates[i]== candidates[i+1]) i++; 

Combination Sum III

void dfscombine(vector<int>& candidates,int level,int& sum,int target,vector<int>& mid,vector<vector<int> >& result,int k)
{
if(sum>target||mid.size()>k) return;
else if(sum==target&&mid.size()==k)
result.push_back(mid);
else
{
for(int i=level;i<candidates.size();i++)
{
sum+=candidates[i];
mid.push_back(candidates[i]);
dfscombine(candidates,i+1,sum,target,mid,result,k);
mid.pop_back();
sum-=candidates[i];
}
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> mid;
vector<vector<int> > result;
vector<int> a(9,0);
for(int i=1;i<10;i++)
a[i-1]=i;
int level=0,sum=0;
dfscombine(a,level,sum,n,mid,result,k);
return result;
}

#### 回溯详解及其应用：Leetcode 39 combination sum

2017-01-31 16:47:37

#### leetcode笔记：Combination Sum

2015-11-25 23:59:24

#### leetcode 39. Combination Sum-回溯算法|递归|非递归

2016-03-15 17:37:26

#### 377. Combination Sum IV-动态规划

2016-09-22 19:54:56

#### 回溯法——combination-sum、combination-sum-ii

2016-05-31 13:27:11

#### 【LeetCode】Combination Sum I & II 解题报告

2014-12-16 11:06:12

#### Leetcode #39. Combination Sum 组合求和 解题报告

2016-04-10 23:42:47

#### [LeetCode39]Combination Sum

2014-06-17 04:15:23

#### [leetcode]40. Combination Sum II ,python实现【medium难度】

2016-06-16 17:37:04

#### Combination Sum算法详解

2015-06-25 17:55:24