Combination Sum I
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]
先排序,然后每次从当前位置开始找下一个数。这里可以先对candidates去重,不过不去重也不影响结果。
1 class Solution {
2 public:
3 vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
4 sort(candidates.begin(), candidates.end());
5 vector<int> r;
6 recursive(candidates, target, 0, r);
7 return ret;
8 }
9
10 void recursive(vector<int> &candidates, int target, int start, vector<int> &r) {
11 if (target <= 0) {
12 if (0 == target) ret.push_back(r);
13 return;
14 }
15
16 for (int i = start; i < candidates.size(); ++i) {
17 //if (i < candidates.size() - 1 && candidates[i] == candidates[i + 1]) continue;
18 r.push_back(candidates[i]);
19 recursive(candidates, target - candidates[i], i, r);
20 r.pop_back();
21 }
22 }
23 private:
24 vector<vector<int> > ret;
25 };
Combination Sum II
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]
这道题和上面类似。但是每个数只能使用一次。如果是重复数,在每个位置上用的应该是第一个数,这样才能保证这个重复数可以重复使用。
比如[1,1,2,3],如果每个位置用的是重复数的最后一个,那么就生成不了[1,1,2]了。
1 class Solution {
2 public:
3 vector<vector<int> > combinationSum2(vector<int> &num, int target) {
4 sort(num.begin(), num.end());
5 vector<int> r;
6 recursive(num, target, 0, r);
7 return ret;
8 }
9
10 void recursive(vector<int> &num, int target, int start, vector<int> &r) {
11 if (target <= 0) {
12 if (0 == target) ret.push_back(r);
13 return;
14 }
15
16 for (int i = start; i < num.size(); ++i) {
17 if (i > start && num[i] == num[i - 1]) continue;
18 r.push_back(num[i]);
19 recursive(num, target - num[i], i + 1, r);
20 r.pop_back();
21 }
22 }
23 private:
24 vector<vector<int> > ret;
25 };
Leetcode | Combination Sum I && II