Advertisement
rishu110067

Untitled

Feb 2nd, 2022 (edited)
1,327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. # Time complexity: O(n * log(n))
  2.  
  3. def generate_all_combinations(arr, target):
  4.    
  5.     def helper(sub,index,partial,result,target,rem_sum):
  6.        
  7.         if target==0:
  8.             result.append(partial)
  9.             return result
  10.        
  11.         if index==len(sub) or target<0 or target>rem_sum:
  12.             return result
  13.        
  14.         # find count of sub[index]
  15.         end = index
  16.         count = 0
  17.         while end<len(sub) and sub[end]==sub[index]:
  18.             end+=1
  19.             count+=1
  20.        
  21.          # include i occurences of sub[index] in partial
  22.         for i in range(0, count+1):
  23.             helper(sub, end, partial + i*[sub[index]], result,target - i*sub[index], rem_sum - count*sub[index])
  24.                
  25.         return result
  26.    
  27.     arr.sort()
  28.     out=helper(arr,0,[],[],target,sum(arr))
  29.     return out
  30.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement