-
Notifications
You must be signed in to change notification settings - Fork 4
/
Combination Sum.txt
59 lines (55 loc) · 1.9 KB
/
Combination Sum.txt
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
problem:
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]
------------------------------------------------------------------------------------------------------
solution:
//如果candidate numbers中含有重复的元素,需要去重先,不过这题说明是set,应该就是指没有重复元素
//因为要求结果组合是有序的,所以集合需先排序,再用递归实现dfs
//每个元素可以被取任意次,因此记录元素的个数也是必要的
void combinationSum_sub(int index, int target, vector<int> &candidates, int *times, vector<vector<int> > &ret)
{
if(target < 0)
return;
if(index == candidates.size())
{
if(target != 0)
return;
}
if(target == 0)
{
vector<int> r;
for(int i = 0; i < index; i++) //这里是从0~index-1
for(int j = 1; j <= times[i]; j++)
r.push_back(candidates[i]);
ret.push_back(r);
return;
}
for(int i = 0; i <= target / candidates[index]; i++)
{
times[index] = i;
combinationSum_sub(index + 1, target - candidates[index] * i, candidates, times, ret);
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
vector<vector<int> > ret;
vector<int> path;
if(candidates.size() == 0)
return ret;
if(target <= 0)
return ret;
sort(candidates.begin(), candidates.end());
int *times = new int[candidates.size()];
for(int i = 0; i < candidates.size(); i++)
times[i] = 0;
combinationSum_sub(0, target, candidates, times, ret);
return ret;
}