imashutosh51

Find all subsets sum of an array

Mar 25th, 2026
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. '''
  2. We are pushing 0 as the first subarray sum which has no elements.
  3. then we will take one element of the array and sum in all the previous subsets, for now
  4. we are having one only, we will do sum of all the elments with 0 seprately and push it into
  5. the ans array so for arr=[1,2,3] our ans was earlier=[0] and now it becomes ans=[0,0+1,0+2,0+3] then
  6. we will go to 2 and again we will do sum of 3 with all the elements and push those as the subsets
  7. so now ans=[0,1,2,3, 1+2, 2+2, 2+3], just keep in mind that new elements should be pushed and need
  8. not to update the previous elements.
  9. '''
  10. class Solution:
  11.     def subsetSums(self, arr):
  12.         ans=[0]
  13.         for i in arr:
  14.             new_sums=[]
  15.             for subset_sum in ans:
  16.                 new_sums.append(i+subset_sum)
  17.             ans=ans+new_sums
  18.         return ans
Advertisement
Add Comment
Please, Sign In to add comment