39. Combination Sum

Post by ailswan Aug.29, 2023

39. Combination Sum

Problem Statement

link: https://leetcode.com/problems/combination-sum/ https://leetcode.cn/problems/combination-sum/

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. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example:

Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]]

Input: candidates = [2], target = 1 Output: []

Solution Approach

Leverage a backtracking strategy to explore viable combinations of the candidates that can sum up to the target.

Algorithm

  1. Sort the candidates to ensure that when backtracking, once a number is deemed too large, all subsequent numbers are too.
  2. In the recursive function findcomb, subtract the current candidate from the current target. If it reaches zero, a valid combination is found.
  3. To avoid duplicate combinations, ensure that during recursion, paths that contain numbers smaller than the last number in the current path are skipped, and only consider numbers in non-decreasing order from the candidates list.

Implement

    class Solution:
      def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
          def findcomb(cur_target, path):
              if cur_target == 0:
                  res.append(path)
              for i, n in enumerate(candidates):
                  if n > cur_target:
                      break
                  if path and n < path[-1]: #added the path here
                      continue
                  findcomb(cur_target - n, path + [n])
                                  
          candidates.sort()
          res = []
          findcomb(target,[])
          return res