题目描述
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]
]
算法1
(回溯法) $O(2^n)$
C++ 代码
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> vec;
dfs(candidates,0,0,target,vec,res);
return res;
}
//因为需保证最后组合结果唯一,dfs必须从n开始,如果之前的搜过,不能往上继续搜,所以这里有个n从n往下搜
void dfs(vector<int>& candidates,int cur,int n,int target,vector<int>&vec,vector<vector<int>>&res){
if(cur>=target){//当前结果大于target返回
if(cur==target)
res.push_back(vec);
return;
}
for(int i=n;i<candidates.size();i++){
vec.push_back(candidates[i]);
dfs(candidates,cur+candidates[i],i,target,vec,res);
vec.pop_back();
}
}
};
It is a best solution I found that very popular and helpful:
https://www.youtube.com/watch?v=4fCRTF9lZcI&ab_channel=EricProgramming