Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

40. Combination Sum II #142

Open
jrmullen opened this issue Jul 1, 2024 · 0 comments
Open

40. Combination Sum II #142

jrmullen opened this issue Jul 1, 2024 · 0 comments

Comments

@jrmullen
Copy link
Owner

jrmullen commented Jul 1, 2024

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        combination = []
        candidates.sort() # Sort `candidates` so we can skip duplicate numbers

        def backtrack(i, target):
            # Base case - the target sum has been exceeded or all `candidates` have been used
            if target <= 0 or i >= len(candidates):
                if target == 0:
                    res.append(combination.copy())
                return

            previous = -99
            # Actions - use each value in `candidates`
            for j in range(i, len(candidates)):
                # Skip duplicates
                if candidates[j] == previous:
                    continue
                combination.append(candidates[j])
                # Backtrack using the next number & calculating the new target
                backtrack(j + 1, target - candidates[j])
                combination.pop()
                previous = candidates[j]

        backtrack(0, target)
        return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant