39. Combination Sum
Problem description:
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.1
2
3
4
5
6
7
8Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
1 | Example 2: |
Solution:
DFS + backtracking.
In backtrack(), I use the following 5 inputs.
- vector<vector
>& res, store every combination here - vector
& temp, this is buffer for recursive, add/remove element depends on depth of dfs - vector
& candidates, - int remain, what we targeting, need to input remain-i when dfs into next level
- int start, this is because we can not have duplicate sets, to record what elements we already passed or visited.
Time complexity: O(n*2^n)
The number of recursive calls, T(n) satisfies the recurrence T(n) = T(n - 1) + T(n - 2) + … + T(1) + T(0),which solves to T(n) = O(2^n). Since we spend O(n) time within a call, the time complexity is O(n2^n);
1 | class Solution: |
1 | class Solution { |
reference:
https://goo.gl/HkoJaT
https://goo.gl/XX6WAv
http://www.1point3acres.com/bbs/thread-117602-1-1.html