imashutosh51

Count of Subsets sum

Mar 5th, 2026 (edited)
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. '''
  2. 0/1 Knapsack-> subset sum exist or not?
  3. There subset sum was returning the True or False but here we need the count of those subsets also
  4. so our dp table will be having the numbers here.and here we are adding the take and not_take cases
  5. to get the total number of subsets
  6.  
  7. Base conditon:
  8. 1.Go till the array complete unlike the subset sum because for eg. {0,0,1} you start
  9. from the right side, so if you get cur==target and then you return, in that case
  10. {0,0,1},{0,1} cases will be missed and {1} this case will be also counter because our
  11. recursion will take the skip those two zeros route.
  12. 2.if cur==target: return 1 saying got one subset
  13. '''
  14. def fun(arr, target, n, dp):
  15.     if n < 0: #if you are going till the n<0 suppose the arr is {0,0,1} so when you reach at the 1st or 0th index there either you will select or not select that will cover {0},{0},{0,0} cases also
  16.         if target == 0:
  17.             return 1
  18.         return 0
  19.  
  20.     if dp[n][target] != -1:
  21.         return dp[n][target]
  22.  
  23.     take, not_take = 0, 0
  24.    
  25.     if arr[n] <= target:
  26.         take = fun(arr, target - arr[n], n - 1, dp)
  27.        
  28.     not_take = fun(arr, target, n - 1, dp)
  29.    
  30.     dp[n][target] = take + not_take
  31.     return dp[n][target]
  32.  
  33.  
  34. class Solution:
  35.     def perfectSum(self, arr, target):
  36.         dp = [[-1] * (target + 1) for _ in range(len(arr))]
  37.         return fun(arr, target, len(arr) - 1, dp)
  38.  
  39.        
Advertisement
Add Comment
Please, Sign In to add comment