Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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].
Algorithm
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
Example
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))
3
How It Works
This solution uses dynamic programming with a 1D array approach:
-
dp[i]represents the number of ways to achieve sum i -
dp[0] = 1because there's one way to make sum 0 (empty subset) - We iterate backwards through possible sums to avoid using updated values
- For each number, we update all possible sums that can include this number
Alternative Approach
Here's a more readable version without class structure ?
def count_subsets_sum_k(nums, k):
MOD = 10**9 + 7
dp = [0] * (k + 1)
dp[0] = 1 # One way to make sum 0 (empty subset)
for num in nums:
for target_sum in range(k, num - 1, -1):
dp[target_sum] = (dp[target_sum] + dp[target_sum - num]) % MOD
return dp[k]
# Test the function
nums = [2, 3, 4, 5, 7]
k = 7
result = count_subsets_sum_k(nums, k)
print(f"Number of subsets that sum to {k}: {result}")
Number of subsets that sum to 7: 3
Conclusion
This dynamic programming approach efficiently counts subsets with a target sum in O(n×k) time complexity. The key insight is using backward iteration to avoid counting the same element multiple times in a single subset.
