

Count of subsets with sum equal to X
source link: https://www.geeksforgeeks.org/count-of-subsets-with-sum-equal-to-x/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Given an array arr[] of length N and an integer X, the task is to find the number of subsets with sum equal to X.
Examples:
Input: arr[] = {1, 2, 3, 3}, X = 6
Output: 3
All the possible subsets are {1, 2, 3},
{1, 2, 3} and {3, 3}Input: arr[] = {1, 1, 1, 1}, X = 1
Output: 4
Approach: A simple approach is to solve this problem by generating all the possible subsets and then checking whether the subset has the required sum. This approach will have exponential time complexity. However, for smaller values of X and array elements, this problem can be solved using dynamic programming.
Let’s look at the recurrence relation first.
dp[i][C] = dp[i + 1][C – arr[i]] + dp[i + 1][C]
Let’s understand the states of the DP now. Here, dp[i][C] stores the number of subsets of the sub-array arr[i…N-1] such that their sum is equal to C.
Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t.
Below is the implementation of the above approach:
- Python3
filter_none
edit
close
play_arrow
link
brightness_4
code
// C++ implementation of the approach
#include <bits/stdc++.h>
using
namespace
std;
#define maxN 20
#define maxSum 50
#define minSum 50
#define base 50
// To store the states of DP
int
dp[maxN][maxSum + minSum];
bool
v[maxN][maxSum + minSum];
// Function to return the required count
int
findCnt(
int
* arr,
int
i,
int
required_sum,
int
n)
{
// Base case
if
(i == n) {
if
(required_sum == 0)
return
1;
else
return
0;
}
// If the state has been solved before
// return the value of the state
if
(v[i][required_sum + base])
return
dp[i][required_sum + base];
// Setting the state as solved
v[i][required_sum + base] = 1;
// Recurrence relation
dp[i][required_sum + base]
= findCnt(arr, i + 1, required_sum, n)
+ findCnt(arr, i + 1, required_sum - arr[i], n);
return
dp[i][required_sum + base];
}
// Driver code
int
main()
{
int
arr[] = { 3, 3, 3, 3 };
int
n =
sizeof
(arr) /
sizeof
(
int
);
int
x = 6;
cout << findCnt(arr, 0, x, n);
return
0;
}
6
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK