# Combination Sum

Combination Sum—LeetCode链接

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

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

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:

[7]
[2, 2, 3] 

还是用到回溯法，这里允许元素重复，约束函数就是当前可能解的sum等于target就行。

C++代码

/*************************************************
Author: Ryan
Date: 2015-11-19
Description: Given a set of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
**************************************************/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

//函数申明
void comb(vector<int> candidates, int index, int sum, int target, vector<vector<int> > &res, vector<int> &path);

vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int> > res;
vector<int> path;
comb(candidates,0,0,target,res,path);
return res;
}
/* 回溯法求所有解，path为一个可行解，res存储所有解向量
* 约束函数为sum==target
* 允许元素重复
*/
void comb(vector<int> candidates, int index, int sum, int target, vector<vector<int> > &res, vector<int> &path)
{
if(sum>target)
return;
if(sum==target){
res.push_back(path);
return;
}
for(int i= index; i<candidates.size();i++)
{
path.push_back(candidates[i]);
comb(candidates,i,sum+candidates[i],target,res,path);
path.pop_back();
}
}

//测试用例
int main() {
int a[] = {2,3,6,7};
vector<int> nums(a,a+4);
int target = 7;
vector<vector<int> > res = combinationSum(nums,target);
cout<<"["<<endl;
for(int i=0;i<res.size();i++) {
cout<<" [";
for(int j=0;j<res[i].size();j++) {
cout<<" "<<res[i][j];
}
cout<<" ]"<<endl;
}
cout<<"]"<<endl;
return 0;
}

运行结果如下图：

• 本文已收录于以下专栏：

## Leetcode|Combination Sum III[回溯]

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

## LeetCode_40---Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations ...

## Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher...

## leetcode【39+40+216+377 Combination Sum 相关】【python】

39Combination Sum是说让我们在给定数组C中找到所有的组合，使得组合中数字的和是target值。并且组合里的数字可以重复，也就是不限制C中每一个数字的使用。 这明显是回溯啦，大家记得让...

## 【LeetCode】 Combination Sum 系列

Combination Sum 【LeetCode】39.Combination Sum 【LeetCode】40.Combination Sum2

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)