-
Notifications
You must be signed in to change notification settings - Fork 4
/
Combination Sum II.txt
66 lines (61 loc) · 1.99 KB
/
Combination Sum II.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
60
61
62
63
64
65
66
problem:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
----------------------------------------------------------------------------------------------------------
solution:
在candidate numbers中包含重复的元素,因此要使解集合里元素唯一,可能需要对重复元素跳过搜索,但是题目又要求每个元素只能最多被取一次,
因此我们统计某个元素出现最大次数,再进行相应的dfs。开始时还是先进行排序。
//////////////////////////////////////////////////////////////////////////////
void combinationSum_sub(int index, int target, int *times, vector<int> &num, vector<vector<int> > &ret)
{
if(target < 0)
return;
if(index == num.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(num[i]);
ret.push_back(r);
return;
}
int maxTimes = 0;
int indexV = index;
while(indexV < num.size() && num[indexV] == num[index])
{
maxTimes++;
indexV++;
}
for(int i = 0; i <= maxTimes; i++)
{
times[index] = i;
combinationSum_sub(indexV, target - num[index] * i, times, num, ret);
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target)
{
vector<vector<int> > ret;
if(num.size() == 0 || target <= 0)
return ret;
int *times = new int[num.size()];
for(int i = 0; i < num.size(); i++)
times[i] = 0;
sort(num.begin(), num.end());
combinationSum_sub(0, target, times, num, ret);
return ret;
}