题目链接:Combination Sum
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]
这道题的要求是给定一组候选数字C和目标数字T,找到所有C中数字的组合,使其和为T。数字可以重复被选。
备注:所有候选数字全为正数,要以非递减方式返回数字组合,结果不包含重复元素。
这道题要求返回所有情况,这是一个NP问题,可以通过回溯方式,逐个找到所有情况。下面是递归处理的代码,可以看到第28、29、30行,就是熟悉的递归回溯代码哦。
时间复杂度:O(???)
空间复杂度:O(nm)(结果数量)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution
{
vector<vector<int> > vvi;
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<int> vi;
combinationSum(candidates, target, 0, vi);
return vvi;
}
private:
void combinationSum(vector<int> &candidates, int target, int i, vector<int> &vi)
{
if(target == 0)
{
vvi.push_back(vi);
return;
}
for(int j = i; j < candidates.size(); ++ j)
{
if(target < candidates[j])
break;
vi.push_back(candidates[j]);
combinationSum(candidates, target - candidates[j], j, vi);
vi.pop_back();
}
}
};