难度:Medium
描述:
Given a set of candidate numbers (C) (without duplicates) 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.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
他要求数组中加起来等于target的组合,这个数可以重复使用。
可以递归地实现,先排序,不断挑可以选的最小的数字。加进一个数组里,看数组和是不是等于target,等于就加到结果中,小于就把它放到数组,进入下一层递归。
代码:
#include <algorithmn>
class Solution {
public:
int T;
int cal(vector<int>& filled){
int res = 0;
for (int i = 0; i < filled.size(); i++){
res += filled[i];
}
return res;
}
void fill(vector<int>& source, vector<int>& filled, vector<vector<int>>& res,int start){
for (int i = start; i < source.size(); i++){
if (cal(filled)+source[i] == T){
filled.push_back(source[i]);
res.push_back(filled);
filled.pop_back();
} else if (cal(filled)+source[i] < T){
filled.push_back(source[i]);
fill(source, filled, res, i);
filled.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
T = target;
sort(candidates.begin(),candidates.end());
vector<int> filled;
vector<vector<int>> res;
fill(candidates,filled,res,0);
return res;
}
};