39. Combination Sum

每日一题 2019 - 03 - 26

题目:

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:

1
2
3
4
5
6
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

Example 2:

1
2
3
4
5
6
7
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

解法:

这个题让我们在给定的数组里面找到与 target 值相等的数字和的序列,简单来说就是递归回溯的思想,从数组里面一个数字出发,深层次遍历所有的分支,也即:

1
2
3
4
5
6
7
8
9
10
11
12
13
if(sum == target) {
res.push_back(ans);
return;
}
else if(sum > target)
return;
else{
for(int i = start; i < nums_len; i++){
ans.push_back(candidates[i]);
dfs(i, sum + candidates[i], target, candidates);
ans.pop_back();
}
}

这个题的解题关键是把回溯的条件要设置清楚,以及要把迭代过程中的暂存 vector 弹出


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector<vector<int>>res;
vector<int>ans;
int nums_len;

vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
if(candidates.empty()) return res;
nums_len = candidates.size();
dfs(0, 0, target, candidates);
return res;
}

void dfs(int start, int sum, int target,vector<int> candidates){
if(sum == target) {
res.push_back(ans); return; }
else if(sum > target)
return;
else{
for(int i = start; i < nums_len; i++){
ans.push_back(candidates[i]);
dfs(i, sum + candidates[i], target, candidates);
ans.pop_back();
}
}
}
};
0%
undefined