- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- if nums[i] <= j, then

- for j in range k down to 0, decrease by 1, do

- return dp[k] mod m

Let us see the following implementation to get better understanding −

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))

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

3

- Related Questions & Answers
- Program to find number of distinct combinations that sum up to k in python
- Partition to K Equal Sum Subsets in C++
- Count subtrees that sum up to a given value x in C++
- Program to count non-empty subsets where sum of min and max element of set is less than k in Python
- Program to count number of paths whose sum is k in python
- Program to find any two numbers in a list that sums up to k in Python
- Python program to get all subsets having sum s\n
- Program to check sum of two numbers is up to k from sorted List or not in Python
- Count subsets that satisfy the given condition in C++
- Count number of ways to partition a set into k subsets in C++
- Program to Find K-Largest Sum Pairs in Python
- How to find the unique combination k sum that corresponds to k sum using C#?
- Program to find sum of rectangle whose sum at most k in Python
- Program to count k length substring that occurs more than once in the given string in Python
- Program to find the sum of largest K sublist in Python

Advertisements