题目:
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]
]
描述:
给出一个无重复元素的数组和一个目标值,数组中的元素之间相加可以得到目标值,求所有的解
其中数组中元素全为正数
分析:
其实是一个完全背包,而且要求所有的解的情况,
最直接的思路就是采用递归的方法,直接暴力,时间复杂度是指数级别,很明显,超时了....
本以为有多项式级别解法,结果看别人的解法也是使用暴力搜索....
看来需要优化一下自己的代码...
结果发现,其实只需要改一句,详情在代码里...
测试数据:
[48,22,49,24,26,47,33,40,37,39,31,46,36,43,45,34,28,20,29,25,41,32,23]
69
[1,3,4]
4
[2,3,9]
1
[2,3,5]
8
[2,3,6,7]
7
代码:(时间复杂度,指数级)
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> result;
vector<int> solution;
findSolution(candidates, target, solution, 0, 0, result);
return result;
}
void findSolution(vector<int>& candidates, int target, vector<int>& solution, int sum, int index, vector<vector<int>> &result) {
if (sum == target) {
result.push_back(solution);
return;
}
if (index == candidates.size()) {
return;
}
findSolution(candidates, target, solution, sum, index + 1, result);
// int max_count = target / candidates[index];//超时代码
int max_count = (target - sum) / candidates[index];
for (int i = 0; i < max_count; ++ i) {
solution.push_back(candidates[index]);
sum += candidates[index];
findSolution(candidates, target, solution, sum, index + 1, result);
}
while (max_count--) {
solution.pop_back();
}
}
};