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.
- 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] ]
题意:输出能加起来等于target的全部组合。
思路:先排序,递归求所有数字的集合,并判断加起来是否等于target
class Solution { public: //先构建递归函数 void CombinationSumCore(const vector<int>& candidates,vector<vector<int>>& res,vector<int>& com,int target,int pos){ if(target==0){ //全是正数,结果不可能是0 res.push_back(com); return; } for(int i=pos;i<candidates.size();i++){ if(candidates[i]>target)break; //如果这个数太大了就放弃。 com.push_back(candidates[i]); CombinationSumCore(candidates,res,com,target-candidates[i],i); //递归(每加入一个数,target就变小一点。) com.pop_back(); //跳过当前的数,并计算下一个数 } } vector<vector<int>> combinationSum(vector<int>& candidates, int target){ sort(candidates.begin(),candidates.end()); //排序 vector<vector<int>> res; //存放结果 vector<int> com; //存放正在计算的数的集合 CombinationSumCore(candidates,res,com,target,0); return res; } };