Title
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,2,3] ] Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
就是回溯法,搜索解空间
Solution
//cpp:
class Solution {
public:
void f(vector<vector<int>> &res,vector<int> &can, vector<int> v, int begin, int target) {
if (target == 0) {
res.push_back(v);
return;
}
if (begin >= can.size()||target<0)
return;
f(res, can, v, begin + 1, target);
for (int i = 1; i*can[begin] <= target; i++) {
v.push_back(can[begin]);
f(res, can, v, begin + 1, target - i*can[begin]);
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> v;
f(res, candidates, v, 0, target);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
return res;
}
};
之所以有个sort是因为结果排序的问题,当然我的没有sort一样通过啦