Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and
target 7,
A solution set is:
[ [7], [2, 2, 3] ]
递归求解
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
dfs(candidates,0,0,target);
return v;
}
private:
vector<vector<int>> v;
vector<int> r;
void dfs(vector<int> vv,int index,int sum,int target){
if(sum>target) return;
if(sum==target) v.push_back(r);
if(index>target) return;
for(int i=0;i<vv.size();i++){
r.push_back(vv[i]);
if(index>=1&&r[index]<r[index-1]) {
r.pop_back();
continue;
}
dfs(vv,index+1,sum+vv[i],target);
r.pop_back();
}
}
};

本文介绍了一种递归算法,用于解决给定候选数集合及目标数时寻找所有可能的组合,使得组合内的数之和等于目标数。该算法允许同一候选数被重复使用,并确保解决方案集中没有重复的组合。
5万+

被折叠的 条评论
为什么被折叠?



