imashutosh51

Partition to K Equal Sum Subsets

Jul 23rd, 2022 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. '''
  2. each bucket size= total_sum/k ie. target
  3. Logic is simple, we will take the elements if cur_sum+nums[i]<=target and pass again for the further elements.if cur_sum==target, means we are done with one bucket so we can iterate again on the nums to fill our another bucket.
  4.  
  5. Few things to maintain:
  6. 1.start with the bigger elements first,it will make it easier because small,small then big might not fit at the end and we will have to reiterate again.
  7. 2.To track which of the elemnets are selected already in the previous bucket, we can keep a used_elements array.
  8. 3.Once bucket size becomes our target, we need to traverse the whole array again and consider only the unused elements.
  9. 4.if cur_sum at the end of the for loop is zero, means even the bigger element couldn't come into the bucket so you can return false.
  10.  
  11. Time Complexity: 2^n for each element selection and k for each bucket so total time complexity is k*2^n
  12. '''
  13.  
  14.  
  15. from typing import List
  16. def dfs(nums, used, start, k, curr_sum, target):
  17.     if k == 1:
  18.         return True
  19.    
  20.     if curr_sum == target:
  21.         return dfs(nums, used, 0, k - 1, 0, target)
  22.    
  23.     for i in range(start, len(nums)):
  24.         if used[i]:
  25.             continue
  26.        
  27.         if curr_sum + nums[i] > target:
  28.             continue
  29.        
  30.         used[i] = True
  31.        
  32.         if dfs(nums, used, i + 1, k, curr_sum + nums[i], target):
  33.             return True
  34.        
  35.         used[i] = False
  36.        
  37.         # pruning
  38.         if curr_sum == 0:
  39.             return False
  40.  
  41.    
  42.     return False
  43.  
  44.  
  45. class Solution:
  46.     def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
  47.         total = sum(nums)
  48.        
  49.         if total % k != 0:
  50.             return False
  51.        
  52.         target = total // k
  53.         nums.sort(reverse=True)  # important
  54.         used = [False] * len(nums)
  55.        
  56.         return dfs(nums, used, 0, k, 0, target)
Advertisement
Add Comment
Please, Sign In to add comment