
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
- 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 −
Example
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
Advertisements