imashutosh51

Subset Sum

Mar 5th, 2026 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. '''
  2. 0/1 knapsack variation: Either take if cur_sum<target or not take
  3. dp table dimension: n*(sum+1) which means rows are 0->n-1 which represents all the element indices
  4. and column represents the sum from 0-> sum so here dp[i][j] will contain either True or False and
  5. it says-> is it possible to get the target using the 0->ith indices elements' sum.
  6.  
  7. Base Case:
  8. 1.cur_sum==Targe->return True
  9. 2.if n<0 return False because we didn't reach target yet
  10. 3.add the current element only when cur_sum<target
  11. '''
  12. def fun(arr, target, n, dp):
  13.     if target == 0:
  14.         return True
  15.        
  16.     if n < 0:
  17.         return False
  18.        
  19.     if dp[n][target] != -1:
  20.         return dp[n][target]
  21.        
  22.     take, not_take = False, False
  23.    
  24.     if arr[n] <= target:
  25.         take = fun(arr, target - arr[n], n - 1, dp)
  26.     not_take = fun(arr, target, n - 1, dp)
  27.    
  28.     dp[n][target] = take or not_take
  29.     return dp[n][target]
  30.    
  31. class Solution:
  32.     def isSubsetSum(self, arr, sum):
  33.         dp = [[-1] * (sum + 1) for _ in range(len(arr))]
  34.         return fun(arr, sum, len(arr) - 1, dp)
  35.        
Advertisement
Add Comment
Please, Sign In to add comment