40. Combination Sum II

Tapan RachchhTapan Rachchh
1 min read
class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        N = len(candidates)
        ans = set()

        def checker(currentSum, nextIndex, nums):
            if currentSum == target:
                t = tuple(nums)
                if t not in ans:
                    ans.add(t)
                return

            if nextIndex >= N or currentSum > target:
                return

            for i in range(nextIndex, N):
                if i > nextIndex and candidates[i] == candidates[i - 1]:
                    continue
                checker(currentSum + candidates[i], i + 1, nums + [candidates[i]])

        checker(0, 0, [])
        return ans
0
Subscribe to my newsletter

Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tapan Rachchh
Tapan Rachchh