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]
]
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> vec;
vector<int> v;
sort(candidates.begin(),candidates.end());
fun(0,candidates,v,vec,target);
return vec;
}
void fun(int begin,vector<int>& candidates,vector<int>& v,vector<vector<int>> &vec,int target)
{
if(target==0) {
vec.push_back(v);
}
else {
for(int i=begin;i!=candidates.size();i++)
if(target>=candidates[i])
{
v.push_back(candidates[i]);
fun(i,candidates,v,vec,target-candidates[i]);
v.pop_back();
}
}
}
};
第一次真正搞懂了回溯递归算法,个人总结一句话:套用框架,灵活应用;
void fun(类型 起始条件,类型 初始结构变量,类型 存储结构变量,类型 迭代变量,....)
{
if(迭代变量终结)
输出结果;
else
{
for(int i = 下界; i <= 上界; i++) 枚举
{
if(迭代值的限制条件) 满足限界函数和约束条件
{
回溯前的工作(push()) ;
fun(类型 起始条件计数值,类型 初始结构变量,类型 存储结构变量,类型 迭代变量,....);
回溯后的清理工作(pop()) ;
}
}
}
}