Leetcode-39 Combination Sum

Combination Sum

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<0,表示该组合不可行,直接返回上一层。若 target==0,说明得到可行组合,将其加入结果集并返回上一层。若 target>0,将其减去当前元素,并递归求解子问题。为避免加入重复组合,在求解子问题时不考虑之前元素。

复杂度分析

略(不会)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
vector<vector<int>> res;
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> sol;
combination(candidates, target, sol, 0);
return res;
}

void combination(vector<int> &candidates, int target, vector<int> &sol, int k) {
if (target < 0) return;
if (target == 0) {
res.push_back(sol);
return;
}
for (int i = k; i < candidates.size(); ++i) {
sol.push_back(candidates[i]);
combination(candidates, target - candidates[i], sol, i);
sol.pop_back();
}
}
};