Given a collection of candidate numbers (candidates)
and a target number (target)
, find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
For the DP approach we create an array of size target+1
where each element i
is a set of all candadiates where sum is equal to i
. The time complexity of this solution is O(N * M^2)
and the space complexity is O(M)
where N
is the length of candidates and M
is the target.
def combinationSum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
:Time Complexity: O(N * M)
:Space Complexity: O(M)
"""
candidates.sort(reverse=False)
dp = [set() for _ in range(target + 1)]
dp[0].add(())
for c in candidates:
for i in reversed(range(c, target + 1)):
if i - c >= 0:
for prev in dp[i - c]:
dp[i].add(prev + (c,))
return dp[-1]