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 −

Example

 Live Demo

class Solution(object):
   def combinationSum(self, candidates, target):
      result = []
      unique={}
      candidates = list(set(candidates))
      self.solve(candidates,target,result,unique)
      return result
   def solve(self,candidates,target,result,unique,i = 0,current=[]):
      if target == 0:
         temp = [i for i in current]
         temp1 = temp
         temp.sort()
         temp = tuple(temp)
         if temp not in unique:
            unique[temp] = 1
            result.append(temp1)
         return
      if target <0:
         return
      for x in range(i,len(candidates)):
         current.append(candidates[x])
         self.solve(candidates,target-candidates[x],result,unique,i,current)
         current.pop(len(current)-1)
ob1 = Solution()
print(ob1.combinationSum([2,3,6,7,8],10))

Input

[2,3,6,7,8]
10

Output

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