Combination Sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have a set of candidate numbers (all elements are unique) and a target number. We have to find all unique combinations in candidates where the candidate numbers sum to the given target. The same repeated number may be chosen from candidates unlimited number of times. So if the elements are [2,3,6,7] and the target value is 7, then the possible output will be [[7], [2,2,3]]

Let us see the steps −

  • We will solve this in recursive manner. The recursive function is named as solve(). This takes an array to store results, one map to keep records, the target value and a list of distinct elements. Initially res array and map is empty. The solve method will work like below −

  • if target is 0, then
    • temp := a list of elements present in the list
    • temp1 := temp, then sort temp
    • if temp is not in the map, then insert temp into map and set value as 1, insert temp into res
    • return
    • if temp < 0, then return
    • for x in range i to length of element list,
      • insert elements[x] into the current
      • solve(elements, target – elements[x], res, map, i, current)
      • delete element from current list from index (length of current – 1)

Let us see the following implementation to get better understanding −


 Live Demo

class Solution(object):
   def combinationSum(self, candidates, target):
      result = []
      candidates = list(set(candidates))
      return result
   def solve(self,candidates,target,result,unique,i = 0,current=[]):
      if target == 0:
         temp = [i for i in current]
         temp1 = temp
         temp = tuple(temp)
         if temp not in unique:
            unique[temp] = 1
      if target <0:
      for x in range(i,len(candidates)):
ob1 = Solution()




[[2, 8], [2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [3, 7]]
Published on 03-Feb-2020 12:15:50