Problem
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 |
|
Example 2:
1 |
|
Explanation 1
-
We can use recursion to solve this problem.
-
First, we create a result list and a sub temporary sublist, passing these two lists as the parameters to the helper function. Also, we pass the start index initialize to 0 to the helper function. The start index is used to avoid duplicate sublist. For example, if
condidates=[1, 2, 3]
, then if we already push the sublist[1, 2]
into the result list, then we don’t want to put[2, 1]
into the result list. In other words, after we finding out all the sublist that starts with 1, we then need to find out all the sublist that starts with 2. -
The base case if
target == 0
, we push the sublist into the result list, and return. If thetarget < 0
, we just return. -
Note, when we push the temporary sublist into the result list, we will pass the new object of temporary sublist, not the reference of original temporary sublist since it will change everytime.
Solution 1
1 |
|
Explanation 2
-
We can also solve this problem using dynamic programming. Let’s use the problem’s Example 1. We first create a dp array
dp[]
anddp[t]
represents all the combinations for targett
. -
Loop through all the candidates, for each candidate
c
, inner loop through targett
from 1 totarget
inclusive. Ifc > t
, we can skip. Else ifc == t
, we find one combination for targett
, which is[c]
, so we append this combination todp[t]
. Else ifc < t
, assumec
is part of the combination, then we need to find all the combinations fordp[t - c]
, and for each combination, we appendc
to it, now this combination become the combination fordp[t]
.
1 |
|
Solution 2
1 |
|