Program to count subsets that sum up to k in python


Suppose we have a list of numbers called nums and another value k, we have to find the number of subsets in the list that sum up to k. If the answer is very large then mod this with 10^9 + 7

So, if the input is like nums = [2, 3, 4, 5, 7] k = 7, then the output will be 3, as We can choose the subsets [2,5],[3,4] and [7].

To solve this, we will follow these steps −

  • dp := a list of size (k + 1) and fill with 0
  • dp[0] := 1
  • m := 10^9 + 7
  • for i in range 0 to size of nums - 1, do
    • for j in range k down to 0, decrease by 1, do
      • if nums[i] <= j, then
        • dp[j] := dp[j] + dp[j - nums[i]]
        • dp[j] := dp[j] mod m
  • return dp[k] mod m

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, nums, k):
      dp = [0] * (k + 1)
      dp[0] = 1
      m = int(1e9 + 7)
      for i in range(len(nums)):
         for j in range(k, -1, -1):
            if nums[i] <= j:
               dp[j] += dp[j - nums[i]]
               dp[j] %= m
      return dp[k] % m

ob = Solution()
nums = [2, 3, 4, 5, 7]
k = 7
print(ob.solve(nums, k))

Input

[2, 3, 4, 5, 7], 7

Output

3

Updated on: 03-Dec-2020

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements