39. Combination Sum
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] ]
题目链接:https://leetcode.com/problems/combination-sum/description/
题目大意:给定一个数组和一个目标数字。求数组中和为目标数字的所有数字组合,数字可以重复相加。
解题思路:dfs递归,到最底层若满足条件就把数字组合加入答案集合。
代码如下:
class Solution {
public:
vector<vector<int> > ans;
vector<int> ca;
int n;
void dfs(int st,vector<int> a,int cur,int target){
if(cur == target){
ans.push_back(a); //a是每个可能的答案,如果最终满足条件,即a中所有数字和为target,则把a加入答案数组
return;
}
if(st >= n)
return;
for(int i = st;i < n;i++){
if(cur + ca[i] <= target){
int num = 1;
vector <int> b = a;
while(cur + ca[i] * num <= target){ //数字可以重复,多次加入同一个数字
b.push_back(ca[i]);
dfs(i + 1,b,cur + ca[i] * num,target); //i是起始位置
num ++;
}
}
}
}
vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
n = candidates.size();
ca = candidates;
vector<int> a;
sort(ca.begin(),ca.end()); //排序
unique(ca.begin(), ca.end()); //去重
dfs(0,a,0,target);
return ans;
}
};