Open In App

Count of subsets with sum equal to X

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a 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. 

Below is the implementation of the above approach: 

C++




// Naive Approach
#include <bits/stdc++.h>
using namespace std;
 
void printBool(int n, int len)
{
 
  while (n) {
    if (n & 1)
      cout << 1;
    else
      cout << 0;
 
    n >>= 1;
    len--;
  }
 
  // This is used for padding zeros
  while (len) {
    cout << 0;
    len--;
  }
  cout << endl;
}
 
// Function
// Prints all the subsets of given set[]
void printSubsetsCount(int set[], int n, int val)
{
  int sum; // it stores the current sum
  int count = 0;
  for (int i = 0; i < (1 << n); i++) {
    sum = 0;
    // Print current subset
    for (int j = 0; j < n; j++)
 
      // (1<<j) is a number with jth bit 1
      // so when we 'and' them with the
      // subset number we get which numbers
      // are present in the subset and which are not
      // Refer :
      if ((i & (1 << j)) > 0) {
        sum += set[j]; // elements are added one by
        // one of a subset to the sum
      }
    // It checks if the sum is equal to desired sum. If
    // it is true then it prints the elements of the sum
    // to the output
    if (sum == val) {
      /*
             * Uncomment printBool(i,n) to get the boolean
             * representation of the selected elements from
             * set. For this example output of this
             * representation will be 0 1 1 1 0 // 2,3,4
             * makes sum 9 1 0 1 0 1 // 1,3,5 also makes sum
             * 9 0 0 0 1 1 // 4,5 also makes sum 9
             *
             * 'i' is used for 'and' operation so the
             * position of set bits in 'i' will be the
             * selected element. and as we have to give
             * padding with zeros to represent the complete
             * set , so length of the set ('n') is passed to
             * the function.
             * */
      //  printBool(i,n);
      count++;
    }
  }
  // it means no subset is found with given sum
  if (count == 0) {
    cout << ("No subset is found") << endl;
  }
  else {
    cout << count << endl;
  }
}
 
// Driver code
int main()
{
  int set[] = { 1, 2, 3, 4, 5 };
  printSubsetsCount(set, 5, 9);
}
 
// This code is contributed by garg28harsh.


C




// Naive Approach
 
#include <stdio.h>
 
void printBool(int n, int len)
{
 
    while (n) {
        if (n & 1)
            printf("1 ");
        else
            printf("0 ");
 
        n >>= 1;
        len--;
    }
 
    // This is used for padding zeros
    while (len) {
        printf("0 ");
        len--;
    }
    printf("\n");
}
 
// Function
// Prints all the subsets of given set[]
void printSubsetsCount(int set[], int n, int val)
{
    int sum; // it stores the current sum
    int count = 0;
    for (int i = 0; i < (1 << n); i++) {
        sum = 0;
        // Print current subset
        for (int j = 0; j < n; j++)
 
            // (1<<j) is a number with jth bit 1
            // so when we 'and' them with the
            // subset number we get which numbers
            // are present in the subset and which are not
            // Refer :
            if ((i & (1 << j)) > 0) {
                sum += set[j]; // elements are added one by
                               // one of a subset to the sum
            }
        // It checks if the sum is equal to desired sum. If
        // it is true then it prints the elements of the sum
        // to the output
        if (sum == val) {
            /*
             * Uncomment printBool(i,n) to get the boolean
             * representation of the selected elements from
             * set. For this example output of this
             * representation will be 0 1 1 1 0 // 2,3,4
             * makes sum 9 1 0 1 0 1 // 1,3,5 also makes sum
             * 9 0 0 0 1 1 // 4,5 also makes sum 9
             *
             * 'i' is used for 'and' operation so the
             * position of set bits in 'i' will be the
             * selected element. and as we have to give
             * padding with zeros to represent the complete
             * set , so length of the set ('n') is passed to
             * the function.
             * */
            //  printBool(i,n);
            count++;
        }
    }
    // it means no subset is found with given sum
    if (count == 0) {
        printf("No subset is found");
    }
    else {
        printf("%d", count);
    }
}
 
// Driver code
void main()
{
    int set[] = { 1, 2, 3, 4, 5 };
    printSubsetsCount(set, 5, 9);
}


Java




import java.io.*;
// Naive Approach
class GFG {
 
    static void printBool(int n, int len)
    {
 
        while (n>0) {
            if ((n & 1) == 1)
                System.out.print(1);
            else
                System.out.print(0);
 
            n >>= 1;
            len--;
        }
 
        // This is used for padding zeros
        while (len>0) {
            System.out.print(0);
            len--;
        }
        System.out.println();
    }
 
    // Function
    // Prints all the subsets of given set[]
    static void printSubsetsCount(int set[], int n, int val)
    {
        int sum; // it stores the current sum
        int count = 0;
        for (int i = 0; i < (1 << n); i++) {
            sum = 0;
            // Print current subset
            for (int j = 0; j < n; j++)
 
                // (1<<j) is a number with jth bit 1
                // so when we 'and' them with the
                // subset number we get which numbers
                // are present in the subset and which are
                // not Refer :
                if ((i & (1 << j)) > 0) {
                    sum += set[j]; // elements are added one
                                   // by
                    // one of a subset to the sum
                }
            // It checks if the sum is equal to desired sum.
            // If it is true then it prints the elements of
            // the sum to the output
            if (sum == val) {
                /*
                 * Uncomment printBool(i,n) to get the
                 * boolean representation of the selected
                 * elements from set. For this example
                 * output of this representation will be 0 1
                 * 1 1 0 // 2,3,4 makes sum 9 1 0 1 0 1 //
                 * 1,3,5 also makes sum 9 0 0 0 1 1 // 4,5
                 * also makes sum 9
                 *
                 * 'i' is used for 'and' operation so the
                 * position of set bits in 'i' will be the
                 * selected element. and as we have to give
                 * padding with zeros to represent the
                 * complete set , so length of the set ('n')
                 * is passed to the function.
                 * */
                //  printBool(i,n);
                count++;
            }
        }
        // it means no subset is found with given sum
        if (count == 0) {
            System.out.println("No subset is found");
        }
        else {
            System.out.println(count);
        }
    }
   
// Driver code
    public static void main(String[] args)
    {
        int set[] = { 1, 2, 3, 4, 5 };
        printSubsetsCount(set, 5, 9);
    }
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Python3




#  Naive Approach
def printBool(n, len):
    while n:
        if n & 1:
            print("1 ")
        else:
            print("0 ")
        n = n >> 1
        len -= 1
 
    #  This is used for padding zeros
    while len:
        print("0 ")
        len -= 1
    print()
 
#  Function
#  Prints all the subsets of given set[]
 
def printSubsetsCount(set, n, val):
    sum = 0  # it stores the current sum
    count = 0
    for i in range(0, 1 << n):
        sum = 0
 
        # Print current subset
        for j in range(0, n):
 
            #  (1<<j) is a number with jth bit 1
            #  so when we 'and' them with the
            #  subset number we get which numbers
            #  are present in the subset and which are not
            #  Refer :
            if (i & 1 << j) > 0:
                sum += set[j]  # elements are added one by
                # one of a subset to the sum
 
        #  It checks if the sum is equal to desired sum. If
        #  it is true then it prints the elements of the sum
        #  to the output
 
        if (sum == val):
            #
            #   Uncomment printBool(i,n) to get the boolean
            #   representation of the selected elements from
            #   set. For this example output of this
            #   representation will be 0 1 1 1 0 // 2,3,4
            #   makes sum 9 1 0 1 0 1 // 1,3,5 also makes sum
            #   9 0 0 0 1 1 // 4,5 also makes sum 9
            #
            #   'i' is used for 'and' operation so the
            #   position of set bits in 'i' will be the
            #   selected element. and as we have to give
            #   padding with zeros to represent the complete
            #   set , so length of the set ('n') is passed to
            #   the function.
            #
            #   printBool(i,n);
            count += 1
 
    #  it means no subset is found with given sum
    if (count == 0):
 
        print("No subset is found")
 
    else:
        print(count)
 
#  Driver code
set = [1, 2, 3, 4, 5]
printSubsetsCount(set, 5, 9)


C#




// Naive Approach
using System;
class GFG {
 
  static void printBool(int n, int len)
  {
 
    while (n > 0) {
      if ((n & 1) == 1)
        Console.Write(1);
      else
        Console.Write(0);
 
      n >>= 1;
      len--;
    }
 
    // This is used for padding zeros
    while (len > 0) {
      Console.Write(0);
      len--;
    }
    Console.WriteLine();
  }
 
  // Function
  // Prints all the subsets of given set[]
  static void printSubsetsCount(int[] set, int n, int val)
  {
    int sum; // it stores the current sum
    int count = 0;
    for (int i = 0; i < (1 << n); i++) {
      sum = 0;
      // Print current subset
      for (int j = 0; j < n; j++)
 
        // (1<<j) is a number with jth bit 1
        // so when we 'and' them with the
        // subset number we get which numbers
        // are present in the subset and which are
        // not Refer :
        if ((i & (1 << j)) > 0) {
          sum += set[j]; // elements are added one
          // by
          // one of a subset to the sum
        }
      // It checks if the sum is equal to desired sum.
      // If it is true then it prints the elements of
      // the sum to the output
      if (sum == val) {
        /*
                 * Uncomment printBool(i,n) to get the
                 * boolean representation of the selected
                 * elements from set. For this example
                 * output of this representation will be 0 1
                 * 1 1 0 // 2,3,4 makes sum 9 1 0 1 0 1 //
                 * 1,3,5 also makes sum 9 0 0 0 1 1 // 4,5
                 * also makes sum 9
                 *
                 * 'i' is used for 'and' operation so the
                 * position of set bits in 'i' will be the
                 * selected element. and as we have to give
                 * padding with zeros to represent the
                 * complete set , so length of the set ('n')
                 * is passed to the function.
                 * */
        //  printBool(i,n);
        count++;
      }
    }
    // it means no subset is found with given sum
    if (count == 0) {
      Console.WriteLine("No subset is found");
    }
    else {
      Console.WriteLine(count);
    }
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int[] set = { 1, 2, 3, 4, 5 };
    printSubsetsCount(set, 5, 9);
  }
}
 
// This code is contributed by Karandeep1234


Javascript




// Naive Approach
 
function printBool( n,  len)
{
 
  while (n!=0) {
    if ((n & 1)!=0)
     console.log(1);
    else
      console.log(0);
 
    n/=2 ;
    len--;
  }
 
  // This is used for padding zeros
  while (len!=0) {
    console.log(0);
    len--;
  }
  cout << endl;
}
 
// Function
// Prints all the subsets of given set[]
function printSubsetsCount(set, n, val)
{
  let sum; // it stores the current sum
  let count = 0;
  for (let i = 0; i < Math.pow(2,n); i++) {
    sum = 0;
    // Print current subset
    for (let j = 0; j < n; j++)
 
      // (1<<j) is a number with jth bit 1
      // so when we 'and' them with the
      // subset number we get which numbers
      // are present in the subset and which are not
      // Refer :
      if ((i & Math.pow(2,j)) > 0) {
        sum += set[j]; // elements are added one by
        // one of a subset to the sum
      }
    // It checks if the sum is equal to desired sum. If
    // it is true then it prints the elements of the sum
    // to the output
    if (sum == val) {
      /*
             * Uncomment printBool(i,n) to get the boolean
             * representation of the selected elements from
             * set. For this example output of this
             * representation will be 0 1 1 1 0 // 2,3,4
             * makes sum 9 1 0 1 0 1 // 1,3,5 also makes sum
             * 9 0 0 0 1 1 // 4,5 also makes sum 9
             *
             * 'i' is used for 'and' operation so the
             * position of set bits in 'i' will be the
             * selected element. and as we have to give
             * padding with zeros to represent the complete
             * set , so length of the set ('n') is passed to
             * the function.
             * */
      //  printBool(i,n);
      count++;
    }
  }
  // it means no subset is found with given sum
  if (count == 0) {
    console.log("No subset is found");
  }
  else {
    console.log(count);
  }
}
 
// Driver code
 
  let set = [ 1, 2, 3, 4, 5 ];
  printSubsetsCount(set, 5, 9);
 
// This code is contributed by garg28harsh.


Output

3

Time Complexity: O(2n), as we are generating all the subsets of the given set. Since there are 2^n subsets, therefore it requires O(2^n) time to generate all the subsets.
Auxiliary Space: O(1), No extra space is required.

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. 

This method is valid for all the integers.

dp[i][C] = dp[i - 1][C - arr[i]] + dp[i - 1][C] 

Let’s understand the state 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: 

C++




// 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;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
static int maxN = 20;
static int maxSum = 50;
static int minSum = 50;
static int base = 50;
 
// To store the states of DP
static int [][]dp = new int[maxN][maxSum + minSum];
static boolean [][]v = new boolean[maxN][maxSum + minSum];
 
// Function to return the required count
static 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] = true;
 
    // 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
public static void main(String []args)
{
    int arr[] = { 3, 3, 3, 3 };
    int n = arr.length;
    int x = 6;
 
    System.out.println(findCnt(arr, 0, x, n));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the approach
import numpy as np
 
maxN = 20
maxSum = 50
minSum = 50
base = 50
 
# To store the states of DP
dp = np.zeros((maxN, maxSum + minSum));
v = np.zeros((maxN, maxSum + minSum));
 
# Function to return the required count
def findCnt(arr, i, required_sum, 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
if __name__ == "__main__" :
 
    arr = [ 3, 3, 3, 3 ];
    n = len(arr);
    x = 6;
 
    print(findCnt(arr, 0, x, n));
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
     
class GFG
{
 
static int maxN = 20;
static int maxSum = 50;
static int minSum = 50;
static int Base = 50;
 
// To store the states of DP
static int [,]dp = new int[maxN, maxSum + minSum];
static Boolean [,]v = new Boolean[maxN, maxSum + minSum];
 
// Function to return the required count
static 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] = true;
 
    // 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
public static void Main(String []args)
{
    int []arr = { 3, 3, 3, 3 };
    int n = arr.Length;
    int x = 6;
 
    Console.WriteLine(findCnt(arr, 0, x, n));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript implementation of the approach
 
var maxN = 20
var maxSum = 50
var minSum = 50
var base = 50
 
// To store the states of DP
var dp = Array.from(Array(maxN),
()=>Array(maxSum+minSum));
var v = Array.from(Array(maxN),
()=>Array(maxSum+minSum));
 
// Function to return the required count
function findCnt(arr, i, required_sum, 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
var arr = [3, 3, 3, 3];
var n = arr.length;
var x = 6;
document.write( findCnt(arr, 0, x, n));
 
</script>


Output

6

Time Complexity: O(n * (maxSum + minSum))

The time complexity of the above approach is O(n*(maxSum + minSum)). Here, n is the size of the given array and maxSum + minSum is the total range of values that the required sum can take.

Space Complexity: O(n * (maxSum + minSum))

The space complexity of the approach is also O(n*(maxSum + minSum)). Here, n is the size of the given array and maxSum + minSum is the total range of values that the required sum can take. We need an extra 2-D array of size n*(maxSum + minSum) to store the states of the DP.

Method 2: Using Tabulation Method:

This method is valid only for those arrays which contains positive elements.
In this method we use a 2D array of size (arr.size() + 1) * (target + 1) of type integer.
Initialization of Matrix:
mat[0][0] = 1 because If the sum is 0 then there exists null subset {} whose sum is 0
if (A[i] > j)
DP[i][j] = DP[i-1][j]
else
DP[i][j] = DP[i-1][j] + DP[i-1][j-A[i]]

This means that if the current element has a value greater than the ‘current sum value’ we will copy the answer for previous cases

And if the current sum value is greater than the ‘ith’ element we will see if any of the previous states have already experienced the sum=’j’ and any previous states experienced a value ‘j – A[i]’ which will solve our purpose

C++




#include <bits/stdc++.h>
using namespace std;
 
int subsetSum(int a[], int n, int sum)
{
    // Initializing the matrix
    int tab[n + 1][sum + 1];
  // Initializing the first value of matrix
    tab[0][0] = 1;
    for (int i = 1; i <= sum; i++)
        tab[0][i] = 0;
     
   
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j <= sum; j++)
        {
          // if the value is greater than the sum
            if (a[i - 1] > j)
                tab[i][j] = tab[i - 1][j];
            else
            {
                tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]];
            }
        }
    }
 
 
    return tab[n][sum];
}
 
int main()
{
    int n = 4;
    int a[] = {3,3,3,3};
    int sum = 6;
 
    cout << (subsetSum(a, n, sum));
}


Java




import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
static int subsetSum(int a[], int n, int sum)
{
     
    // Initializing the matrix
    int tab[][] = new int[n + 1][sum + 1];
 
    // Initializing the first value of matrix
    tab[0][0] = 1;
 
    for(int i = 1; i <= sum; i++)
        tab[0][i] = 0;
 
 
    for(int i = 1; i <= n; i++)
    {
        for(int j = 0; j <= sum; j++)
        {
             
            // If the value is greater than the sum
            if (a[i - 1] > j)
                tab[i][j] = tab[i - 1][j];
 
            else
            {
                tab[i][j] = tab[i - 1][j] +
                            tab[i - 1][j - a[i - 1]];
            }
        }
    }
 
    return tab[n][sum];
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 4;
    int a[] = { 3, 3, 3, 3 };
    int sum = 6;
 
    System.out.print(subsetSum(a, n, sum));
}
}
 
// This code is contributed by Kingash


Python3




def subset_sum(a: list, n: int, sum: int):
   
    # Initializing the matrix
    tab = [[0] * (sum + 1) for i in range(n + 1)]
    tab[0][0] = 1
    for i in range(1, sum + 1):
        tab[0][i] = 0
     
    for i in range(1, n+1):
        for j in range(sum + 1):
            if a[i-1] <= j:
                tab[i][j] = tab[i-1][j] + tab[i-1][j-a[i-1]]
            else:
                tab[i][j] = tab[i-1][j]
    return tab[n][sum]
 
if __name__ == '__main__':
    a = [3, 3, 3, 3]
    n = 4
    sum = 6
    print(subset_sum(a, n, sum))
 
    # This code is contributed by Premansh2001.


C#




using System;
 
class GFG{
 
static int subsetSum(int []a, int n, int sum)
{
     
    // Initializing the matrix
    int [,]tab = new int[n + 1, sum + 1];
 
    // Initializing the first value of matrix
    tab[0, 0] = 1;
 
    for(int i = 1; i <= sum; i++)
        tab[0, i] = 0;
 
 
    for(int i = 1; i <= n; i++)
    {
        for(int j = 0; j <= sum; j++)
        {
             
            // If the value is greater than the sum
            if (a[i - 1] > j)
                tab[i, j] = tab[i - 1, j];
            else
            {
                tab[i, j] = tab[i - 1, j] +
                            tab[i - 1, j - a[i - 1]];
            }
        }
    }
    return tab[n, sum];
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 4;
    int []a = { 3, 3, 3, 3 };
    int sum = 6;
 
    Console.Write(subsetSum(a, n, sum));
}
}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
 
 
function subsetSum( a,  n, sum)
{
    // Initializing the matrix
    var tab = new Array(n + 1);
    for (let i = 0; i< n+1; i++)
      tab[i] = new Array(sum + 1);
  // Initializing the first value of matrix
    tab[0][0] = 1;
    for (let i = 1; i <= sum; i++)
        tab[0][i] = 0;
 
    for (let i = 1; i <= n; i++)
    {
        for (let j = 0; j <= sum; j++)
        {
          // if the value is greater than the sum
            if (a[i - 1] > j)
                tab[i][j] = tab[i - 1][j];
            else
            {
                tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]];
            }
        }
    }
 
 
    return tab[n][sum];
}
 
var n = 4;
var a = new Array(3,3,3,3);
var sum = 6;
 
console.log(subsetSum(a, n, sum));
 
// This code is contributed by ukasp.
</script>


Output

6

Time Complexity: O(sum*n), where the sum is the ‘target sum’ and ‘n’ is the size of the array.
Auxiliary Space: O(sum*n), as the size of the 2-D array, is sum*n. 

What if the value of elements starts from 0? 

In the case of elements with value 0, your answer can be incorrect with the above solution. Here’s the reason why:-

Consider the below example:

arr[] = {0,1,1,1}

target sum = 3

correct output : 2

As you can see from the dp table, if there is a 0 in the array then it will not take part in the count if it is in the starting position (dp[1][1]).

 

but if the zero is at the end of the array, then the table would be:

 

So just sort the array in descending order to achieve the correct output.

Method 3: Space Optimization:

We can solve this problem by just taking care of last state and current state so we can wrap up this problem in O(target+1) space complexity.

Example:-

vector<int> arr = { 3, 3, 3, 3 }; with targetSum of 6;

dp[0][arr[0]] — tells about what if at index 0 we need arr[0] to achieve the targetSum and fortunately we have that solve so mark them 1;

=====dp[0][3]=1

target

Index

0 1 2 3 4 5 6
0 1 0 0 1 0 0 0
1 1 0 0 2 0 0 1
2 1 0 0 3 0 0 3
3 1 0 0 4 0 0 6
at dp[2][6] --- tells tell me is at index 2 can count some subsets with sum=6, How can we achieve this?
so we can tell ok i have reached at index 2 by adding element of index 1 or not both case has been added ------ means dp[i-1] we need only bcoz we are need of last index decision only nothing more than that so this why we are using a huge 2D array
just store our running state and last state that's it.

1.Time Complexity:- O(N*val)
2.Space Complexity:- O(Val)
where val and n are targetSum and number of element.

C++




#include <bits/stdc++.h>
using namespace std;
 
int CountSubsetSum(vector<int>& arr, int val, int n)
{
    vector<int> PresentState(val + 1, 0),
        LastState(val + 1, 0);
    // consider only last and present state we dont need the
    // (present-2)th state and above and we know for val to
    // be 0 if we dont pick the current index element we can
    // achieve
    PresentState[0] = LastState[0] = 1;
    if (arr[0] <= val)
        LastState[arr[0]] = 1;
    for (int i = 1; i < n; i++) {
        for (int j = 1; j <= val; j++)
            PresentState[j]
                = ((j >= arr[i]) ? LastState[j - arr[i]]
                                 : 0)
                  + LastState[j];
        // this we will need in the next iteration so just
        // swap current and last state.
        LastState = PresentState;
    }
    // Note after exit from loop we will having a present
    // state which is nothing but the laststate itself;
    return PresentState[val]; // or return
                              // CurrentState[val];
}
int main()
{
    vector<int> arr = { 3, 3, 3, 3 };
    cout << CountSubsetSum(arr, 6, arr.size());
}


Java




import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    static int subsetSum(int arr[], int n, int val)
    {
 
        int[] LastState = new int[val + 1];
        // consider only last and present state we dont need
        // the (present-2)th state and above and we know for
        // val to be 0 if we dont pick the current index
        // element we can achieve
 
        LastState[0] = 1;
        if (arr[0] <= val) {
            LastState[arr[0]] = 1;
        }
        for (int i = 1; i < n; i++) {
            int[] PresentState = new int[val + 1];
            PresentState[0] = 1;
            for (int j = 1; j <= val; j++) {
 
                int notPick = LastState[j];
                int pick = 0;
                if (arr[i] <= j)
                    pick = LastState[j - arr[i]];
 
                PresentState[j] = pick + notPick;
            }
            // this we will need in the next iteration so
            // just swap current and last state.
            LastState = PresentState;
        }
        // Note after exit from loop we will having a
        // present state which is nothing but the laststate
        // itself;
        return LastState[val]; // or return
                               // CurrentState[val];
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 4;
        int a[] = { 3, 3, 3, 3 };
        int sum = 6;
 
        System.out.print(subsetSum(a, n, sum));
    }
}
 
// This code is contributed by Sanskar


Python3




def CountSubsetSum( arr, val, n):
 
    LastState=[0]*(val + 1);
    # consider only last and present state we dont need the
    # (present-2)th state and above and we know for val to
    # be 0 if we dont pick the current index element we can
    # achieve
    LastState[0] = 1;
    if (arr[0] <= val):
        LastState[arr[0]] = 1;
    for i in range(1,n):
        PresentState=[0]*(val + 1);
        PresentState[0]=1;
        for j in range(1,val+1):
            if(j >= arr[i]):               
                PresentState[j] = LastState[j - arr[i]]+ LastState[j];
            else:
                PresentState[j] = LastState[j]
                 
        # this we will need in the next iteration so just
        # swap current and last state.
        LastState = PresentState;
    # Note after exit from loop we will having a present
    # state which is nothing but the laststate itself;
    return PresentState[val]; # or return
                              # CurrentState[val];
                               
arr = [ 3, 3, 3, 3 ];
print(CountSubsetSum(arr, 6, len(arr)));


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;           
 
class GFG
{
 
  static int subsetSum(int[] arr, int n, int val)
  {
 
    int[] LastState = new int[val + 1];
    // consider only last and present state we dont need
    // the (present-2)th state and above and we know for
    // val to be 0 if we dont pick the current index
    // element we can achieve
 
    LastState[0] = 1;
    if (arr[0] <= val) {
      LastState[arr[0]] = 1;
    }
    for (int i = 1; i < n; i++) {
      int[] PresentState = new int[val + 1];
      PresentState[0] = 1;
      for (int j = 1; j <= val; j++) {
 
        int notPick = LastState[j];
        int pick = 0;
        if (arr[i] <= j)
          pick = LastState[j - arr[i]];
 
        PresentState[j] = pick + notPick;
      }
      // this we will need in the next iteration so
      // just swap current and last state.
      LastState = PresentState;
    }
    // Note after exit from loop we will having a
    // present state which is nothing but the laststate
    // itself;
    return LastState[val]; // or return
    // CurrentState[val];
  }
 
  // Driver code
  public static void Main (String[] args)
  {
    int n = 4;
    int[] a = { 3, 3, 3, 3 };
    int sum = 6;
 
    Console.WriteLine(subsetSum(a, n, sum));
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




function countSubsetSum(arr, val, n) {
    let presentState = new Array(val + 1).fill(0);
     
    // consider only last and present state we dont need the (present-2)th
    // state and above and we know for val to be 0 if we dont pick the
    // current index element we can achieve
    let lastState = new Array(val + 1).fill(0);
    presentState[0] = lastState[0] = 1;
    if (arr[0] <= val) {
        lastState[arr[0]] = 1;
    }
     
    for (let i = 1; i < n; i++) {
        for (let j = 1; j <= val; j++) {
            presentState[j] = ((j >= arr[i]) ? lastState[j - arr[i]] : 0) + lastState[j];
            // this we will need in the next iteration so just swap current and last state.
        }
        lastState = [...presentState];
    }
     
    // Note after exit from loop we will having a present
    // state which is nothing but the laststate itself;
    return presentState[val]; // or return CurrentState[val];
}
 
let arr = [3, 3, 3, 3];
console.log(countSubsetSum(arr, 6, arr.length));
 
// This code is contributed by ritaagarwal.


Output

6

Time Complexity: O(sum*n), where the sum is the ‘target sum’ and ‘n’ is the size of the array.
Auxiliary Space: O(sum). 



Last Updated : 28 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads