Problem : 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.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
My Solution :
Since this is a backtracking problem, I went ahead with a dfs approach where i check each subsequence along with its sum and accordingly generate the result. For handling the duplicate solutions issue, I sort the temp array before adding it into the resulting set result in the form of a tuple.
But here's the thing; my approach if working fine for the 1st example but there's a weird issue I'm facing with the 2nd example.
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(ind, temp, sum):
if ind >= n:
if sum == target:
temp.sort()
result.add(tuple(temp))
return
if sum < target:
temp.append(candidates[ind])
sum += candidates[ind]
dfs(ind + 1, temp, sum)
temp.pop()
sum -= candidates[ind]
dfs(ind + 1, temp, sum)
temp, n = [], len(candidates)
result = set()
dfs(0, temp, 0)
return result
The 1st example runs well, but here's the output I'm getting for the 2nd example:
candidates =
[2,5,2,1,2]
target =
5
Output
[[1,2,2],[5],[1,1,2]]
Expected
[[1,2,2],[5]]
There is this weird tuple (1,1,2) getting added to the resultant set when there's only one 1 present in the input array. I tried debugging but so far no clue.
Can someone help me figure out where I'm going wrong?
............................
Here is an answer inspired by your original code using backtracking.