版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82221819
算法描述:
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]
]
算法实现:
采用回溯法进行递归,对于每一个元素,要尝试如果不用这个元素,在其余元素中能不能找到解;以及如果用这个元素能不能在这个元素及剩余元素中找到和为(target-这个元素值)的解。为防止解重复,可以将元素按照大小排列,对于每个相应元素和当前目标只在之后寻找相应解。值得注意的是不管能不能找到相应解,要恢复现场,进行下一次尝试,因为可能有多组解。
class Solution {
public:
bool combination(vector<int>& candidates, int target, int index_min, vector<int> &oneres, vector<vector<int>> &res){
if(index_min >= candidates.size())return false;
if(candidates[index_min] > target)return false;
if(candidates[index_min] == target){
oneres.push_back(candidates[index_min]);
res.push_back(oneres);
oneres.pop_back();
return true;
}
bool flag = combination(candidates, target, index_min + 1, oneres, res);
oneres.push_back(candidates[index_min]);
//不用写while循环,将所有的7-2,7-2-2,7-2-2-2等都写入其中
if(combination(candidates, target - candidates[index_min], index_min, oneres, res))
flag = true;
oneres.pop_back();
return flag;
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
if(candidates.empty())return res;
vector<int> oneres;
combination(candidates, target, 0, oneres, res);
return res;
}
};