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]
题意:将数组中的元素(可以重复)任意组合使其和为target。在网上找到的做法基本上都是用DFS算法,也有说到类似背包问题,额,我又忘掉背包问题怎么解了,记笔记记笔记 ><。
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> path;
comb(candidates, 0, 0, path, res, target);
return res;
}
private:
void comb(vector<int>& candidates,int index,int sum,vector<int> &path,vector<vector<int>> &res,int target) {
if (sum > target) return;
else if (sum == target)
{
res.push_back(path);
int n = res.size()-1;
sort(res[n].begin(), res[n].end());
return;
}
for (int i = index; i < candidates.size(); i++) {
path.push_back(candidates[i]);
comb(candidates, i, sum + candidates[i], path, res, target);
path.pop_back();
}
return;
}
};
set 2,3,6,7 and target 7。DFS算法的递归过程如下:
2 | 2 2 | 2 2 2 | 2 2 2 2 |
---|---|---|---|
2 2 2 3 | |||
2 2 2 6 | |||
2 2 2 7 | |||
2 2 3 | |||
2 2 6 | |||
2 2 7 | |||
2 3 | 2 3 3 | ||
2 3 6 | |||
2 3 7 | |||
2 6 | |||
2 7 | |||
3 | 3 3 | 3 3 3 | |
3 3 6 | |||
3 3 7 | |||
3 6 | |||
3 7 | |||
6 | 6 6 | ||
6 7 | |||
7 |
Combination Sum II
2相对于1的区别是:combination中的数字有重复且未排序。最后得到的集合里每个数字只能出现一次。对于数字不能重复出现的问题,只需要将comb函数中的递归过程的index变为i+1,就不会重复。
第二个需要解决的问题是,如果combination中有重复数字时,最后得到的vector还是会有重复。所以这里笔者想到的解决办法就是,先用map容器存储得到的vector,如果有重复则无法插入。最后再将map容器中的元素push_back到vector<vector<int>>
中。
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
map<vector<int>,int> res;
vector<vector<int>> result;
vector<int> path;
comb(candidates, 0, 0, path, res, target);
for (map<vector<int>, int>::iterator it = res.begin(); it != res.end();it++) {
result.push_back(it->first);
}
return result;
}
private:
void comb(vector<int>& candidates,int index,int sum,vector<int> &path, map<vector<int>, int> &res,int target) {
if (sum > target) return;
else if (sum == target)
{
vector<int> key = path;
sort(key.begin(), key.end());
res.insert(map<vector<int>, int>::value_type(key, 0));
return;
}
for (int i = index; i < candidates.size(); i++) {
path.push_back(candidates[i]);
comb(candidates, i+1, sum + candidates[i], path, res, target);
path.pop_back();
}
return;
}
};