leetcode相关C++算法解答: https://github.com/Nereus-Minos/C_plus_plus-leetcode
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的数字可以无限制重复被选取。
说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。
输入: candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ]
输入: candidates = [2,3,5], target = 8, 所求解集为: [[2,2,2,2],[2,3,3],[3,5] ]
使用递归回溯的方法求出所有接
关于去重方法:1.使用map(太复杂,且效果不好)2.在递归的时候将start也传入
#if 0
//思路:为了避免重复,使用map去重
class Solution {
public:
vector> combinationSum(vector& candidates, int target) {
vector> ret;
vector temp;
map, int> ret_temp; //为了去重
search_combine(candidates, temp, ret_temp, target, 0);
for(map, int>::iterator iter = ret_temp.begin(); iter != ret_temp.end(); iter++) //iter != ret_temp.end()没有重载<比较符,所以只能用!=
ret.push_back((*iter).first);
return ret;
}
private:
void search_combine(vector& candidates, vector temp, map, int>& ret_temp, int& target, int count){
if(count == target)
{
sort(temp.begin(), temp.end());
if(ret_temp.find(temp) == ret_temp.end())
ret_temp[temp] = 1;
return ;
}
else if(count > target)
return ;
else
{
for(int i = 0; i < candidates.size(); i++)
{
temp.push_back(candidates[i]);
count += candidates[i];
search_combine(candidates, temp, ret_temp, target, count);
temp.erase(temp.end()-1);
count -= candidates[i];
}
}
}
};
#endif
#if 1
//思路:为了避免重复,需要在递归的时候将start也传入
class Solution {
public:
vector> combinationSum(vector& candidates, int target) {
vector> ret;
vector temp;
sort(candidates.begin(), candidates.end());
search_combine(candidates, temp, ret, target, 0, 0);
return ret;
}
private:
void search_combine(vector& candidates, vector temp, vector>& ret, int& target, int count, int start){
if(count == target)
{
ret.push_back(temp);
return ;
}
else if(count > target)
return ;
else
{
for(int i = start; i < candidates.size(); i++)
{
temp.push_back(candidates[i]);
count += candidates[i];
search_combine(candidates, temp, ret, target, count, i);
temp.erase(temp.end()-1);
count -= candidates[i];
}
}
}
};
#endif