my slack is getting o/p as slack=[[],[],[]] output is not appending in it why?
candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
type here
class Solution:
def __init__(self):
self.slack =[]
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
output =[]
i =0
def rec(i,target,output,candidates):
if i>=len(candidates):
if target == 0:
self.slack.append(output)
return self.slack
if candidates[i]<=target:
output.append(candidates[i])
rec(i+1,target-candidates[i],output,candidates)
output.pop()
rec(i+1,target,output,candidates)
rec(i,target,output,candidates)
return self.slack
output needs to be appended inside the slack
>Solution :
Try this
from typing import List
class Solution:
def __init__(self):
self.slack = []
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
output = []
i = 0
candidates.sort() # Sort the candidates list to handle duplicates
def rec(i, target, output, candidates):
if i >= len(candidates):
if target == 0:
self.slack.append(output.copy()) # Append a copy of 'output' to 'self.slack'
return self.slack
if candidates[i] <= target:
output.append(candidates[i])
rec(i + 1, target - candidates[i], output, candidates)
# Skip duplicates
while i + 1 < len(candidates) and candidates[i] == candidates[i + 1]:
i += 1
output.pop() # Remove the last element as we backtrack
rec(i + 1, target, output, candidates)
rec(i, target, output, candidates)
return self.slack
Testing
candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
solution = Solution()
result = solution.combinationSum2(candidates, target)
print(result) # [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
assert result == [[1,1,6], [1,2,5], [1,7], [2,6]]