您的位置:首页 > 其它

Leetcode | Combination Sum I && II

2014-05-18 11:28 337 查看

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]

先排序,然后每次从当前位置开始找下一个数。去下重,不过貌似leetcode的testcases没有针对这个。

class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int> > ans;
if (candidates.empty()) return ans;
vector<int> tmp;
sort(candidates.begin(), candidates.end());
recurse(candidates, 0, target, tmp, ans);
return ans;
}
void recurse(vector<int> &candidates, int start, int target, vector<int> &tmp, vector<vector<int> > &ans) {
if (target < 0) return;
if (target == 0) {
ans.push_back(tmp);
return;
}

for (int i = start; i < candidates.size(); i++) {
tmp.push_back(candidates[i]);
recurse(candidates, i, target - candidates[i], tmp, ans);
tmp.pop_back();
}
}
};


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]了。

class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(), num.end());
vector<int> r;
recursive(num, target, 0, r);
return ret;
}

void recursive(vector<int> &num, int target, int start, vector<int> &r) {
if (target <= 0) {
if (0 == target) ret.push_back(r);
return;
}

for (int i = start; i < num.size(); ++i) {
if (i > start && num[i] == num[i - 1]) continue;
r.push_back(num[i]);
recursive(num, target - num[i], i + 1, r);
r.pop_back();
}
}
private:
vector<vector<int> > ret;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: