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
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40
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:
- Initialize left and right pointers to the start and end of the array, respectively.
- 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.
- If the target is not found, return left.
Complexity
- Time Complexity: O(2^n)
- Space Complexity: O(n)
Code copied to clipboard!