LeetSolved

Find solutions to all LeetCode problems here.

39.

Combination Sum

Medium

Problem Description

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.

Examples

Input: [2,3,6,7], 7
Output: [[2,2,3],[7]]

Input: [2,3,5], 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Input: [2], 1
Output: []

Constraints

Approach to Solve

Use a two-pointer approach to find the target.

Code Implementation

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def backtrack(start, target, path):
            if target == 0:
                result.append(path[:])
                return
            for i in range(start, len(candidates)):
                if candidates[i] > target:
                    break
                path.append(candidates[i])
                backtrack(i, target - candidates[i], path)
                path.pop()
        
        result = []
        candidates.sort()
        backtrack(0, target, [])
        return result

Explanation

This solution uses a two-pointer approach to find the target. Here's a detailed explanation of the algorithm:

  1. Initialize left and right pointers to the start and end of the array, respectively.
  2. While left is less than or equal to right:
    • Calculate the middle index mid.
    • If nums[mid] is equal to the target, return mid.
    • If nums[mid] is less than the target, move the left pointer to mid + 1.
    • Otherwise, move the right pointer to mid - 1.
  3. If the target is not found, return left.

Complexity

  • Time Complexity: O(2^n)
  • Space Complexity: O(n)
Code copied to clipboard!