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]
]
思路:深度优先搜索。
排列组合的多解问题容易想到dfs,这一题是一个很标准的dfs模版,排序以后,dfs函数参数设置为输入、中间结果、结果、判断依据、起始位置。dfs函数中判断差为0时返回,差小于当前数字时剪枝,然后每压入一个数字,递归调用一次dfs,不行就弹出。
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<vector<int>>result;
vector<int>path;
dfs(nums,path,result,target,0);
return result;
}
void dfs(vector<int>&nums,vector<int>&path,vector<vector<int>>&result,int gap,int start){
if(!gap){
result.push_back(path);
return;
}
for(int i=start;i<nums.size();i++){
if(gap<nums[i]) return;
path.push_back(nums[i]);
dfs(nums,path,result,gap-nums[i],i);
path.pop_back();
}
}
};