The Wayback Machine - https://web.archive.org/web/20240930193305/https://www.geeksforgeeks.org/subset-sum-problem-dp-25/
Open In App

Subset Sum Problem

Last Updated : 16 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. 

Examples: 

Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True
Explanation: There is a subset (4, 5) with sum 9.

Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30
Output: False
Explanation: There is no subset that add up to 30.

Subset Sum Problem using Recursion:

For the recursive approach, there will be two cases. 

  • Consider the ‘last’ element to be a part of the subset. Now the new required sum = required sum – value of ‘last’ element.
  • Don’t include the ‘last’ element in the subset. Then the new required sum = old required sum.

In both cases, the number of available elements decreases by 1.

Mathematically the recurrence relation will look like the following:

isSubsetSum(set, n, sum) = isSubsetSum(set, n-1, sum) | isSubsetSum(set, n-1, sum-set[n-1])

Base Cases:
isSubsetSum(set, n, sum) = false, if sum > 0 and n = 0
isSubsetSum(set, n, sum) = true, if sum = 0

The structure of the recursion tree will be like the following:

Structure of the recursion tree of the above recursion formula

Structure of the recursion tree of the above recursion formula

Follow the below steps to implement the recursion:

  • Build a recursive function and pass the index to be considered (here gradually moving from the last end) and the remaining sum amount.
  • For each index check the base cases and utilize the above recursive call.
  • If the answer is true for any recursion call, then there exists such a subset. Otherwise, no such subset exists.

Below is the implementation of the above approach.

C++
// A recursive solution for subset sum problem

#include <bits/stdc++.h>
using namespace std;

// Returns true if there is a subset
// of set[] with sum equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
    // Base Cases
    if (sum == 0)
        return true;
    if (n == 0)
        return false;

    // If last element is greater than sum,
    // then ignore it
    if (set[n - 1] > sum)
        return isSubsetSum(set, n - 1, sum);

    // Else, check if sum can be obtained by any
    // of the following:
    // (a) including the last element
    // (b) excluding the last element
    return isSubsetSum(set, n - 1, sum)
           || isSubsetSum(set, n - 1, sum - set[n - 1]);
}

// Driver code
int main()
{
    int set[] = { 3, 34, 4, 12, 5, 2 };
    int sum = 9;
    int n = sizeof(set) / sizeof(set[0]);
    if (isSubsetSum(set, n, sum) == true)
        cout << "Found a subset with given sum";
    else
        cout << "No subset with given sum";
    return 0;
}

// This code is contributed by shivanisinghss2110
C
// A recursive solution for subset sum problem

#include <stdio.h>
#include <stdbool.h>

// Returns true if there is a subset
// of set[] with sum equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
    // Base Cases
    if (sum == 0)
        return true;
    if (n == 0)
        return false;

    // If last element is greater than sum,
    // then ignore it
    if (set[n - 1] > sum)
        return isSubsetSum(set, n - 1, sum);

    // Else, check if sum can be obtained by any
    // of the following:
    // (a) including the last element
    // (b) excluding the last element
    return isSubsetSum(set, n - 1, sum)
           || isSubsetSum(set, n - 1, sum - set[n - 1]);
}

// Driver code
int main()
{
    int set[] = { 3, 34, 4, 12, 5, 2 };
    int sum = 9;
    int n = sizeof(set) / sizeof(set[0]);
    if (isSubsetSum(set, n, sum) == true)
        printf("Found a subset with given sum");
    else
        printf("No subset with given sum");
    return 0;
}
Java
// A recursive solution for subset sum

import java.io.*;
class GFG {

    // Returns true if there is a subset
    // of set[] with sum equal to given sum
    static boolean isSubsetSum(int set[], int n, int sum)
    {
        // Base Cases
        if (sum == 0)
            return true;
        if (n == 0)
            return false;

        // If last element is greater than
        // sum, then ignore it
        if (set[n - 1] > sum)
            return isSubsetSum(set, n - 1, sum);

        // Else, check if sum can be obtained
        // by any of the following
        // (a) including the last element
        // (b) excluding the last element
        return isSubsetSum(set, n - 1, sum)
            || isSubsetSum(set, n - 1, sum - set[n - 1]);
    }

    // Driver code
    public static void main(String args[])
    {
        int set[] = { 3, 34, 4, 12, 5, 2 };
        int sum = 9;
        int n = set.length;
        if (isSubsetSum(set, n, sum) == true)
            System.out.println("Found a subset"
                               + " with given sum");
        else
            System.out.println("No subset with"
                               + " given sum");
    }
}

/* This code is contributed by Rajat Mishra */
Python
# A recursive solution for subset sum
# problem


# Returns true if there is a subset
# of set[] with sun equal to given sum
def isSubsetSum(set, n, sum):

    # Base Cases
    if (sum == 0):
        return True
    if (n == 0):
        return False

    # If last element is greater than
    # sum, then ignore it
    if (set[n - 1] > sum):
        return isSubsetSum(set, n - 1, sum)

    # Else, check if sum can be obtained
    # by any of the following
    # (a) including the last element
    # (b) excluding the last element
    return isSubsetSum(
        set, n-1, sum) or isSubsetSum(
        set, n-1, sum-set[n-1])


# Driver code
if __name__ == '__main__':
    set = [3, 34, 4, 12, 5, 2]
    sum = 9
    n = len(set)
    if (isSubsetSum(set, n, sum) == True):
        print("Found a subset with given sum")
    else:
        print("No subset with given sum")

# This code is contributed by Nikita Tiwari.
C#
// A recursive solution for subset sum problem

using System;

class GFG {

    // Returns true if there is a subset of set[]
    // with sum equal to given sum
    static bool isSubsetSum(int[] set, int n, int sum)
    {
        // Base Cases
        if (sum == 0)
            return true;
        if (n == 0)
            return false;

        // If last element is greater than sum,
        // then ignore it
        if (set[n - 1] > sum)
            return isSubsetSum(set, n - 1, sum);

        // Else, check if sum can be obtained
        // by any of the following
        // (a) including the last element
        // (b) excluding the last element
        return isSubsetSum(set, n - 1, sum)
            || isSubsetSum(set, n - 1, sum - set[n - 1]);
    }

    // Driver code
    public static void Main()
    {
        int[] set = { 3, 34, 4, 12, 5, 2 };
        int sum = 9;
        int n = set.Length;
        if (isSubsetSum(set, n, sum) == true)
            Console.WriteLine(
                "Found a subset with given sum");
        else
            Console.WriteLine("No subset with given sum");
    }
}

// This code is contributed by Sam007
JavaScript
<script>
    // A recursive solution for subset sum problem
    
    // Returns true if there is a subset of set[] with sum
    // equal to given sum
    function isSubsetSum(set, n, sum)
    {
        // Base Cases
        if (sum == 0)
            return true;
        if (n == 0)
            return false;
 
        // If last element is greater than sum,
        // then ignore it
        if (set[n - 1] > sum)
            return isSubsetSum(set, n - 1, sum);
 
        // Else, check if sum can be obtained
        // by any of the following
        // (a) including the last element
        // (b) excluding the last element
        return isSubsetSum(set, n - 1, sum)
          || isSubsetSum(set, n - 1, sum - set[n - 1]);
    }
    
    let set = [ 3, 34, 4, 12, 5, 2 ];
    let sum = 9;
    let n = set.length;
    if (isSubsetSum(set, n, sum) == true)
      document.write("Found a subset with given sum");
    else
      document.write("No subset with given sum");
    
    // This code is contributed by mukesh07.
</script>
PHP
<?php
// A recursive solution for subset sum problem

// Returns true if there is a subset of set
// with sun equal to given sum
function isSubsetSum($set, $n, $sum)
{
    // Base Cases
    if ($sum == 0)
        return true;
    if ($n == 0)
        return false;
    
    // If last element is greater
    // than sum, then ignore it
    if ($set[$n - 1] > $sum)
        return isSubsetSum($set, $n - 1, $sum);
    
    // Else, check if sum can be 
    // obtained by any of the following
    // (a) including the last element
    // (b) excluding the last element
    return isSubsetSum($set, $n - 1, $sum) || 
        isSubsetSum($set, $n - 1, 
                    $sum - $set[$n - 1]);
}

// Driver Code
$set = array(3, 34, 4, 12, 5, 2);
$sum = 9;
$n = 6;

if (isSubsetSum($set, $n, $sum) == true)
    echo"Found a subset with given sum";
else
    echo "No subset with given sum";
    
// This code is contributed by Anuj_67 
?>

Output
Found a subset with given sum

Complexity Analysis: 

  • Time Complexity: O(2n) The above solution may try all subsets of the given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem).
  • Auxiliary Space: O(n) where n is recursion stack space.

Subset Sum Problem using Memoization:

As seen in the previous recursion method, each state of the solution can be uniquely identified using two variables – the index and the remaining sum. So create a 2D array to store the value of each state to avoid recalculation of the same state.

Below is the implementation of the above approach:

C++
// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Taking the matrix as globally
int tab[2000][2000];

// Check if possible subset with 
// given sum is possible or not
int subsetSum(int a[], int n, int sum)
{   
    // If the sum is zero it means 
    // we got our expected sum
    if (sum == 0)
        return 1;
        
    if (n <= 0)
        return 0;
  
    // If the value is not -1 it means it 
    // already call the function 
    // with the same value.
    // it will save our from the repetition.
    if (tab[n - 1][sum] != -1)
        return tab[n - 1][sum];
  
    // If the value of a[n-1] is
    // greater than the sum.
    // we call for the next value
    if (a[n - 1] > sum)
        return tab[n - 1][sum] = subsetSum(a, n - 1, sum);
    else
    {      
        // Here we do two calls because we 
        // don't know which value is 
        // full-fill our criteria
        // that's why we doing two calls
        return tab[n - 1][sum] = subsetSum(a, n - 1, sum) || 
                       subsetSum(a, n - 1, sum - a[n - 1]);
    }
}

// Driver Code
int main()
{
    // Storing the value -1 to the matrix
    memset(tab, -1, sizeof(tab));
    int n = 5;
    int a[] = {1, 5, 3, 7, 4};
    int sum = 12;

    if (subsetSum(a, n, sum))
    {
        cout << "YES" << endl;
    }
    else
        cout << "NO" << endl;
  
    /* This Code is Contributed by Ankit Kumar*/
}
Java
// Java program for the above approach
import java.io.*;
class GFG {

    // Check if possible subset with
    // given sum is possible or not
    static int subsetSum(int a[], int n, int sum)
    {
        // Storing the value -1 to the matrix
        int tab[][] = new int[n + 1][sum + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
                tab[i][j] = -1;
            }
        }

        // If the sum is zero it means
        // we got our expected sum
        if (sum == 0)
            return 1;

        if (n <= 0)
            return 0;

        // If the value is not -1 it means it
        // already call the function
        // with the same value.
        // it will save our from the repetition.
        if (tab[n - 1][sum] != -1)
            return tab[n - 1][sum];

        // If the value of a[n-1] is
        // greater than the sum.
        // we call for the next value
        if (a[n - 1] > sum)
            return tab[n - 1][sum]
                = subsetSum(a, n - 1, sum);
        else {

            // Here we do two calls because we
            // don't know which value is
            // full-fill our criteria
            // that's why we doing two calls
            if (subsetSum(a, n - 1, sum) != 0
                || subsetSum(a, n - 1, sum - a[n - 1])
                       != 0) {
                return tab[n - 1][sum] = 1;
            }
            else
                return tab[n - 1][sum] = 0;
        }
    }

      // Driver Code
    public static void main(String[] args)
    {
        int n = 5;
        int a[] = { 1, 5, 3, 7, 4 };
        int sum = 12;

        if (subsetSum(a, n, sum) != 0) {
            System.out.println("YES\n");
        }
        else
            System.out.println("NO\n");
    }
}

// This code is contributed by rajsanghavi9.
Python
# Python program for the above approach

# Taking the matrix as globally
tab = [[-1 for i in range(2000)] for j in range(2000)]


# Check if possible subset with
# given sum is possible or not
def subsetSum(a, n, sum):

    # If the sum is zero it means
    # we got our expected sum
    if (sum == 0):
        return 1

    if (n <= 0):
        return 0

    # If the value is not -1 it means it
    # already call the function
    # with the same value.
    # it will save our from the repetition.
    if (tab[n - 1][sum] != -1):
        return tab[n - 1][sum]

    # If the value of a[n-1] is
    # greater than the sum.
    # we call for the next value
    if (a[n - 1] > sum):
        tab[n - 1][sum] = subsetSum(a, n - 1, sum)
        return tab[n - 1][sum]
    else:

        # Here we do two calls because we
        # don't know which value is
        # full-fill our criteria
        # that's why we doing two calls
        tab[n - 1][sum] = subsetSum(a, n - 1, sum)
        return tab[n - 1][sum] or subsetSum(a, n - 1, sum - a[n - 1])


# Driver Code
if __name__ == '__main__':
    n = 5
    a = [1, 5, 3, 7, 4]
    sum = 12
    if (subsetSum(a, n, sum)):
        print("YES")
    else:
        print("NO")

# This code is contributed by shivani.
C#
// C# program for the above approach
using System;

class GFG 
{
    // Check if possible subset with
    // given sum is possible or not
    static int subsetSum(int []a, int n, int sum)
    {     
        // Storing the value -1 to the matrix
        int [,]tab = new int[n + 1,sum + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
                tab[i,j] = -1;
            }
        }

        // If the sum is zero it means
        // we got our expected sum
        if (sum == 0)
            return 1;

        if (n <= 0)
            return 0;

        // If the value is not -1 it means it
        // already call the function
        // with the same value.
        // it will save our from the repetition.
        if (tab[n - 1,sum] != -1)
            return tab[n - 1,sum];

        // If the value of a[n-1] is
        // greater than the sum.
        // we call for the next value
        if (a[n - 1] > sum)
            return tab[n - 1,sum]
                = subsetSum(a, n - 1, sum);
        else {

            // Here we do two calls because we
            // don't know which value is
            // full-fill our criteria
            // that's why we doing two calls
            if (subsetSum(a, n - 1, sum) != 0
                || subsetSum(a, n - 1, sum - a[n - 1])
                       != 0) {
                return tab[n - 1,sum] = 1;
            }
            else
                return tab[n - 1,sum] = 0;
        }
    }

      // Driver Code
    public static void Main(String[] args)
    {
        int n = 5;
        int []a = { 1, 5, 3, 7, 4 };
        int sum = 12;

        if (subsetSum(a, n, sum) != 0) {
            Console.Write("YES\n");
        }
        else
            Console.Write("NO\n");
    }
}

// This code is contributed by shivanisinghss2110
JavaScript
 <script>
 
        // JavaScript Program for the above approach


        // Check if possible subset with 
        // given sum is possible or not
        function subsetSum(a, n, sum) {

            // If the sum is zero it means 
            // we got our expected sum
            if (sum == 0)
                return 1;

            if (n <= 0)
                return 0;

            // If the value is not -1 it means it 
            // already call the function 
            // with the same value.
            // it will save our from the repetition.
            if (tab[n - 1][sum] != -1)
                return tab[n - 1][sum];

            // If the value of a[n-1] is
            // greater than the sum.
            // we call for the next value
            if (a[n - 1] > sum)
                return tab[n - 1][sum] = subsetSum(a, n - 1, sum);
            else {

                // Here we do two calls because we 
                // don't know which value is 
                // full-fill our criteria
                // that's why we doing two calls
                return tab[n - 1][sum] = subsetSum(a, n - 1, sum) ||
                    subsetSum(a, n - 1, sum - a[n - 1]);
            }
        }

        // Driver Code

        // Storing the value -1 to the matrix
        let tab = Array(2000).fill().map(() => Array(2000).fill(-1));

        let n = 5;
        let a = [1, 5, 3, 7, 4];
        let sum = 12;

        if (subsetSum(a, n, sum)) {
            document.write("YES" + "<br>");
        }
        else {
            document.write("NO" + "<br>");
        }

    // This code is contributed by Potta Lokesh

</script>

Output
YES

Complexity Analysis: 

  • Time Complexity: O(sum*n), where sum is the ‘target sum’ and ‘n’ is the size of array.
  • Auxiliary Space: O(sum*n) + O(n) -> O(sum*n) = the size of 2-D array is sum*n and O(n)=auxiliary stack space.

Subset Sum Problem using Dynamic Programming:

To solve the problem in Pseudo-polynomial time we can use the Dynamic programming approach.

So we will create a 2D array of size (n + 1) * (sum + 1) of type boolean. The state dp[i][j] will be true if there exists a subset of elements from set[0 . . . i] with sum value = ‘j’. 

The dynamic programming relation is as follows: 

if (A[i-1] > j)
    dp[i][j] = dp[i-1][j]
else 
    dp[i][j] = dp[i-1][j] OR dp[i-1][j-set[i-1]]

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 OR any previous states experienced a value ‘j – set[i]’ which will solve our purpose.

Illustration:

See the below illustration for a better understanding:

Consider set[] = {3, 4, 5, 2} and sum = 6.

The table will look like the following where the column number represents the sum and the row number represents the index of set[]:

 

0

1

2

3

4

5

6

no element (0)

T

F

F

F

F

F

F

0 (3)

T

F

F

T

F

F

F

1 (4)

T

F

F

T

T

F

F

2 (5)

T

F

F

T

T

T

F

3 (2)

T

F

T

T

T

T

T

Below is the implementation of the above approach: 

C++
// A Dynamic Programming solution
// for subset sum problem
#include <bits/stdc++.h>
using namespace std;

// Returns true if there is a subset of set[]
// with sum equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
    // The value of subset[i][j] will be true if
    // there is a subset of set[0..i-1] with sum
    // equal to j
    bool subset[n + 1][sum + 1];

    // If sum is 0, then answer is true
    for (int i = 0; i <= n; i++)
        subset[i][0] = true;

    // If sum is not 0 and set is empty,
    // then answer is false
    for (int i = 1; i <= sum; i++)
        subset[0][i] = false;

    // Fill the subset table in bottom up manner
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= sum; j++) {
            if (j < set[i - 1])
                subset[i][j] = subset[i - 1][j];
            if (j >= set[i - 1])
                subset[i][j]
                    = subset[i - 1][j]
                      || subset[i - 1][j - set[i - 1]];
        }
    }

    return subset[n][sum];
}

// Driver code
int main()
{
    int set[] = { 3, 34, 4, 12, 5, 2 };
    int sum = 9;
    int n = sizeof(set) / sizeof(set[0]);
    if (isSubsetSum(set, n, sum) == true)
        cout << "Found a subset with given sum";
    else
        cout << "No subset with given sum";
    return 0;
}
C
// A Dynamic Programming solution
// for subset sum problem
#include <stdio.h>
#include <stdbool.h>

// Returns true if there is a subset of set[]
// with sum equal to given sum
bool isSubsetSum(int set[], int n, int sum)
{
    // The value of subset[i][j] will be true if
    // there is a subset of set[0..j-1] with sum
    // equal to i
    bool subset[n + 1][sum + 1];

    // If sum is 0, then answer is true
    for (int i = 0; i <= n; i++)
        subset[i][0] = true;

    // If sum is not 0 and set is empty,
    // then answer is false
    for (int i = 1; i <= sum; i++)
        subset[0][i] = false;

    // Fill the subset table in bottom up manner
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= sum; j++) {
            if (j < set[i - 1])
                subset[i][j] = subset[i - 1][j];
            if (j >= set[i - 1])
                subset[i][j]
                    = subset[i - 1][j]
                      || subset[i - 1][j - set[i - 1]];
        }
    }

    return subset[n][sum];
}

// Driver code
int main()
{
    int set[] = { 3, 34, 4, 12, 5, 2 };
    int sum = 9;
    int n = sizeof(set) / sizeof(set[0]);
    if (isSubsetSum(set, n, sum) == true)
        printf("Found a subset with given sum");
    else
        printf("No subset with given sum");
    return 0;
}
// This code is contributed by Arjun Tyagi.
Java
// A Dynamic Programming solution for subset
// sum problem
import java.io.*;
class GFG {

    // Returns true if there is a subset of
    // set[] with sum equal to given sum
    static boolean isSubsetSum(int set[], int n, int sum)
    {
        // The value of subset[i][j] will be
        // true if there is a subset of
        // set[0..j-1] with sum equal to i
        boolean subset[][] = new boolean[sum + 1][n + 1];

        // If sum is 0, then answer is true
        for (int i = 0; i <= n; i++)
            subset[0][i] = true;

        // If sum is not 0 and set is empty,
        // then answer is false
        for (int i = 1; i <= sum; i++)
            subset[i][0] = false;

        // Fill the subset table in bottom
        // up manner
        for (int i = 1; i <= sum; i++) {
            for (int j = 1; j <= n; j++) {
                subset[i][j] = subset[i][j - 1];
                if (i >= set[j - 1])
                    subset[i][j]
                        = subset[i][j]
                          || subset[i - set[j - 1]][j - 1];
            }
        }

        return subset[sum][n];
    }

    // Driver code
    public static void main(String args[])
    {
        int set[] = { 3, 34, 4, 12, 5, 2 };
        int sum = 9;
        int n = set.length;
        if (isSubsetSum(set, n, sum) == true)
            System.out.println("Found a subset"
                               + " with given sum");
        else
            System.out.println("No subset with"
                               + " given sum");
    }
}

/* This code is contributed by Rajat Mishra */
Python
# A Dynamic Programming solution for subset
# sum problem Returns true if there is a subset of
# set[] with sun equal to given sum


# Returns true if there is a subset of set[]
# with sum equal to given sum
def isSubsetSum(set, n, sum):

    # The value of subset[i][j] will be
    # true if there is a
    # subset of set[0..j-1] with sum equal to i
    subset = ([[False for i in range(sum + 1)]
               for i in range(n + 1)])

    # If sum is 0, then answer is true
    for i in range(n + 1):
        subset[i][0] = True

    # If sum is not 0 and set is empty,
    # then answer is false
    for i in range(1, sum + 1):
        subset[0][i] = False

    # Fill the subset table in bottom up manner
    for i in range(1, n + 1):
        for j in range(1, sum + 1):
            if j < set[i-1]:
                subset[i][j] = subset[i-1][j]
            if j >= set[i-1]:
                subset[i][j] = (subset[i-1][j] or
                                subset[i - 1][j-set[i-1]])

    return subset[n][sum]


# Driver code
if __name__ == '__main__':
    set = [3, 34, 4, 12, 5, 2]
    sum = 9
    n = len(set)
    if (isSubsetSum(set, n, sum) == True):
        print("Found a subset with given sum")
    else:
        print("No subset with given sum")

# This code is contributed by
# sahil shelangia.
C#
// A Dynamic Programming solution for
// subset sum problem
using System;

class GFG {
    
    // Returns true if there is a subset
    // of set[] with sum equal to given sum
    static bool isSubsetSum(int[] set, int n, int sum)
    {
        // The value of subset[i][j] will be true if there
        // is a subset of set[0..j-1] with sum equal to i
        bool[, ] subset = new bool[sum + 1, n + 1];

        // If sum is 0, then answer is true
        for (int i = 0; i <= n; i++)
            subset[0, i] = true;

        // If sum is not 0 and set is empty,
        // then answer is false
        for (int i = 1; i <= sum; i++)
            subset[i, 0] = false;

        // Fill the subset table in bottom up manner
        for (int i = 1; i <= sum; i++) {
            for (int j = 1; j <= n; j++) {
                subset[i, j] = subset[i, j - 1];
                if (i >= set[j - 1])
                    subset[i, j]
                        = subset[i, j]
                          || subset[i - set[j - 1], j - 1];
            }
        }

        return subset[sum, n];
    }

    // Driver code
    public static void Main()
    {
        int[] set = { 3, 34, 4, 12, 5, 2 };
        int sum = 9;
        int n = set.Length;
        if (isSubsetSum(set, n, sum) == true)
            Console.WriteLine(
                "Found a subset with given sum");
        else
            Console.WriteLine("No subset with given sum");
    }
}
// This code is contributed by Sam007
JavaScript
<script>
    // A Dynamic Programming solution for subset sum problem
    
    // Returns true if there is a subset of
    // set[] with sum equal to given sum
    function isSubsetSum(set, n, sum)
    {
        // The value of subset[i][j] will be
        // true if there is a subset of
        // set[0..j-1] with sum equal to i
        let subset = new Array(sum + 1);
        
        for(let i = 0; i < sum + 1; i++)
        {
            subset[i] = new Array(sum + 1);
            for(let j = 0; j < n + 1; j++)
            {
                subset[i][j] = 0;
            }
        }
 
        // If sum is 0, then answer is true
        for (let i = 0; i <= n; i++)
            subset[0][i] = true;
 
        // If sum is not 0 and set is empty,
        // then answer is false
        for (let i = 1; i <= sum; i++)
            subset[i][0] = false;
 
        // Fill the subset table in bottom
        // up manner
        for (let i = 1; i <= sum; i++) {
            for (let j = 1; j <= n; j++) {
                subset[i][j] = subset[i][j - 1];
                if (i >= set[j - 1])
                    subset[i][j] = subset[i][j]
                                   || subset[i - set[j - 1]][j - 1];
            }
        }
 
        return subset[sum][n];
    }
    
    let set = [ 3, 34, 4, 12, 5, 2 ];
    let sum = 9;
    let n = set.length;
    if (isSubsetSum(set, n, sum) == true)
      document.write("Found a subset" + " with given sum");
    else
      document.write("No subset with" + " given sum");
    
    // This code is contributed by decode2207.
</script>
PHP
<?php
// A Dynamic Programming solution for 
// subset sum problem

// Returns true if there is a subset of
// set[] with sum equal to given sum
function isSubsetSum( $set, $n, $sum)
{
    // The value of subset[i][j] will
    // be true if there is a subset of
    // set[0..j-1] with sum equal to i
    $subset = array(array());

    // If sum is 0, then answer is true
    for ( $i = 0; $i <= $n; $i++)
        $subset[$i][0] = true;

    // If sum is not 0 and set is empty,
    // then answer is false
    for ( $i = 1; $i <= $sum; $i++)
        $subset[0][$i] = false;

    // Fill the subset table in bottom
    // up manner
    for ($i = 1; $i <= $n; $i++)
    {
        for ($j = 1; $j <= $sum; $j++)
        {
            if($j < $set[$i-1])
                $subset[$i][$j] = 
                      $subset[$i-1][$j];
            if ($j >= $set[$i-1])
                $subset[$i][$j] = 
                       $subset[$i-1][$j] || 
                       $subset[$i - 1][$j - 
                               $set[$i-1]];
        }
    }

    return $subset[$n][$sum];
}

// Driver code
$set = array(3, 34, 4, 12, 5, 2);
$sum = 9;
$n = count($set);

if (isSubsetSum($set, $n, $sum) == true)
    echo "Found a subset with given sum";
else
    echo "No subset with given sum";

// This code is contributed by anuj_67.
?>

Output
Found a subset with given sum

Complexity Analysis:

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

Subset Sum Problem using Dynamic Programming with space optimization to linear:

Idea:

In previous approach of dynamic programming we have derive the relation between states as given below:

if (arr[i-1] > j)
    dp[i][j] = dp[i-1][j]
else 
    dp[i][j] = dp[i-1][j] OR dp[i-1][j-arr[i-1]]

If we observe that for calculating current dp[i][j] state we only need previous row dp[i-1][j] or dp[i-1][j-arr[i-1]].

There is no need to store all the previous states just one previous state is used to compute result.

Approach:

  • Define two arrays prev and curr of size Sum+1 to store the just previous row result and current row result respectively.
  • Once curr array is calculated then curr becomes our prev for the next row.
  • When all rows are processed the answer is stored in prev array.

Implementation of the above approach:

C++
// C++ Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem
#include <bits/stdc++.h>
using namespace std;

// Returns true if there is a subset of set[]
// with sum equal to given sum
bool isSubsetSum(vector<int> arr, int sum)
{
    int n = arr.size();
    // vector to store the current state and previous state
    vector<bool> prev(sum + 1, false), curr(sum + 1);

    // Mark prev[0] = true as it is true to make sum = 0
    // using 0 elements
    prev[0] = true;

    // Fill the subset table in bottom up manner
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j <= sum; j++) {
            if (j < arr[i - 1])
                curr[j] = prev[j];
            else
                curr[j] = (prev[j] || prev[j - arr[i - 1]]);
        }
        prev = curr;
    }
    return prev[sum];
}

// Driver code
int main()
{
    vector<int> arr = { 3, 34, 4, 12, 5, 2 };
    int sum = 9;
    if (isSubsetSum(arr, sum) == true)
        cout << "Found a subset with given sum";
    else
        cout << "No subset with given sum";
    return 0;
}
Java
// Java Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem

import java.util.*;

public class SubsetSum {

    // Returns true if there is a subset of set[]
    // with sum equal to given sum
    static boolean isSubsetSum(ArrayList<Integer> arr, int sum) {
        int n = arr.size();
        // vector to store the current state and previous state
        boolean[] prev = new boolean[sum + 1];
        boolean[] curr = new boolean[sum + 1];

        // Mark prev[0] = true as it is true to make sum = 0
        // using 0 elements
        prev[0] = true;

        // Fill the subset table in bottom up manner
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                if (j < arr.get(i - 1))
                    curr[j] = prev[j];
                else
                    curr[j] = (prev[j] || prev[j - arr.get(i - 1)]);
            }
            prev = curr.clone();
        }
        return prev[sum];
    }

    // Driver code
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(3, 34, 4, 12, 5, 2));
        int sum = 9;
        if (isSubsetSum(arr, sum))
            System.out.println("Found a subset with given sum");
        else
            System.out.println("No subset with given sum");
    }
}
Python
# Python Program for Space Optimized Dynamic Programming
# Solution to Subset Sum Problem

# Returns true if there is a subset of set[]
# with sum equal to given sum
def isSubsetSum(arr, sum):
    n = len(arr)
    # List to store the current state and previous state
    prev = [False] * (sum + 1)
    curr = [False] * (sum + 1)

    # Mark prev[0] = True as it is true to make sum = 0
    # using 0 elements
    prev[0] = True

    # Fill the subset table in bottom up manner
    for i in range(1, n + 1):
        for j in range(sum + 1):
            if j < arr[i - 1]:
                curr[j] = prev[j]
            else:
                curr[j] = prev[j] or prev[j - arr[i - 1]]
        prev = curr[:]

    return prev[sum]

# Driver code
if __name__ == "__main__":
    arr = [3, 34, 4, 12, 5, 2]
    sum_val = 9
    if isSubsetSum(arr, sum_val):
        print("Found a subset with given sum")
    else:
        print("No subset with given sum")
C#
// C# Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem

using System;
using System.Collections.Generic;

public class SubsetSum
{
    // Returns true if there is a subset of set[]
    // with sum equal to given sum
    static bool IsSubsetSum(List<int> arr, int sum)
    {
        int n = arr.Count;
        // Array to store the current state and previous state
        bool[] prev = new bool[sum + 1];
        bool[] curr = new bool[sum + 1];

        // Mark prev[0] = true as it is true to make sum = 0
        // using 0 elements
        prev[0] = true;

        // Fill the subset table in bottom up manner
        for (int i = 1; i <= n; i++)
        {
            for (int j = 0; j <= sum; j++)
            {
                if (j < arr[i - 1])
                    curr[j] = prev[j];
                else
                    curr[j] = prev[j] || prev[j - arr[i - 1]];
            }
            Array.Copy(curr, prev, curr.Length); // Copy curr to prev
        }

        return prev[sum];
    }

    // Driver code
    public static void Main(string[] args)
    {
        List<int> arr = new List<int> { 3, 34, 4, 12, 5, 2 };
        int sum = 9;
        if (IsSubsetSum(arr, sum))
            Console.WriteLine("Found a subset with given sum");
        else
            Console.WriteLine("No subset with given sum");
    }
}
JavaScript
// JavaScript Program for Space Optimized Dynamic Programming
// Solution to Subset Sum Problem

// Returns true if there is a subset of set[]
// with sum equal to given sum
function isSubsetSum(arr, sum) {
    let n = arr.length;
    // Array to store the current state and previous state
    let prev = new Array(sum + 1).fill(false);
    let curr = new Array(sum + 1).fill(false);

    // Mark prev[0] = true as it is true to make sum = 0
    // using 0 elements
    prev[0] = true;

    // Fill the subset table in bottom up manner
    for (let i = 1; i <= n; i++) {
        for (let j = 0; j <= sum; j++) {
            if (j < arr[i - 1])
                curr[j] = prev[j];
            else
                curr[j] = prev[j] || prev[j - arr[i - 1]];
        }
        prev = [...curr]; // Copy curr to prev
    }

    return prev[sum];
}

// Driver code
let arr = [3, 34, 4, 12, 5, 2];
let sum = 9;
if (isSubsetSum(arr, sum))
    console.log("Found a subset with given sum");
else
    console.log("No subset with given sum");

Output
Found a subset with given sum

Complexity Analysis:

  • Time Complexity: O(sum * n), where n is the size of the array.
  • Auxiliary Space: O(sum), as the size of the 1-D array is sum+1.

Related Articles:



Similar Reads

Minimum Subset sum difference problem with Subset partitioning
Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If the size is even, both subsets will have the same
13 min read
Sum of maximum and minimum of Kth subset ordered by increasing subset sum
Given an integer N and a set of all non-negative powers of N as S = {N0, N1, N2, N3, ... }, arrange all non-empty subsets of S in increasing order of subset-sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering. Examples: Input: N = 4, K = 3Output: 5Explanation: S = {1, 4, 16, 64, ...}.Therefore
7 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
15+ min read
Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 2 1 2 The req
8 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Subset sum problem where Array sum is at most N
Given an array arr[] of size N such that the sum of all the array elements does not exceed N, and array queries[] containing Q queries. For each query, the task is to find if there is a subset of the array whose sum is the same as queries[i]. Examples: Input: arr[] = {1, 0, 0, 0, 0, 2, 3}, queries[] = {3, 7, 6}Output: PossibleNot PossiblePossibleEx
10 min read
Subset Sum Problem in O(sum) space
Given an array of non-negative integers and a value sum, determine if there is a subset of the given set with sum equal to given sum. Examples: Input: arr[] = {4, 1, 10, 12, 5, 2}, sum = 9Output: TRUEExplanation: {4, 5} is a subset with sum 9. Input: arr[] = {1, 8, 2, 5}, sum = 4Output: FALSE Explanation: There exists no subset with sum 4. Recommen
13 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Maximum size of subset such that product of all subset elements is a factor of N
Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all elements of the subset is a factor of 12. They are {2
6 min read
Subset Sum Problem using Backtracking
Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:  Input: set[] = {1,2,1}, sum = 3Output: [1,2],[2,1]Explanation: There are subsets [1,2],[2,1] with sum 3. Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30Output: []Explanation: There is no subset that
8 min read
Prime Subset Product Problem
Given an array arr[] of N integers. The value of a subset of array A is defined as the product of all prime numbers in that subset. If there are no primes in the subset then the value of that subset is 1. The task is to calculate the product of values of all possible non-empty subsets of the given array modulus 100000007.Examples: Input: arr[] = {3
7 min read
Largest subset having with sum less than equal to sum of respective indices
Given an array arr[], the task is to find the length of the largest subset with the sum of elements less than or equal to the sum of its indexes(1-based indexing). Examples: Input: arr[] = {1, 7, 3, 5, 9, 6, 6} Output: 5 Explanation: Largest Subset is {1, 3, 5, 6, 6} Sum of indexes = 1 + 3 + 4 + 6 + 7 = 21 Sum of elements = 1 + 3 + 5 + 6 + 6 = 21 I
8 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Maximum size subset with given sum
This is an extended version of the subset sum problem. Here we need to find the size of the maximum size subset whose sum is equal to the given sum. Examples: Input : set[] = {2, 3, 5, 7, 10, 15}, sum = 10 Output : 3 The largest sized subset with sum 10 is {2, 3, 5} Input : set[] = {1, 2, 3, 4, 5} sum = 4 Output : 2 This is the further enhancement
8 min read
Largest subset with sum of every pair as prime
Given an array A[], find a subset of maximum size in which sum of every pair of elements is a prime number. Print its length and the subset. Consider many queries for different arrays and maximum value of an element as 100000. Examples : Input : A[] = {2, 1, 2} Output : 2 1 2 Explanation : Here, we can only form subsets with size 1 and 2. maximum s
13 min read
Fibonacci sum of a subset with all elements <= k
Given an array of n elements, the task is to find the fibonacci sum of a subset of the array where every element of the subset <= k. Precisely, find F(Ai1) + F(Ai2) + F(Ai3) + … + F(Aix)), where (Ai1, Ai2, …, Aix) <= K and 1 <= (i1, i2, …, ix) <= n. Here, F(i) is the ith Fibonacci number Examples : Input : arr = {1, 2, 3, 4, 2, 7} Query
15+ min read
Subset array sum by generating all the subsets
Given an array of size N and a sum, the task is to check whether some array elements can be added to sum to N . Note: At least one element should be included to form the sum.(i.e. sum cant be zero) Examples: Input: array = -1, 2, 4, 121, N = 5 Output: YES The array elements 2, 4, -1 can be added to sum to N Input: array = 1, 3, 7, 121, N = 5 Output
5 min read
Subset Sum Queries in a Range using Bitset
Given an array[] of N positive integers and M queries. Each query consists of two integers L and R represented by a range. For each query, find the count of numbers that lie in the given range which can be expressed as the sum of any subset of given array. Prerequisite : Subset Sum Queries using Bitset Examples: Input : arr[] = { 1, 2, 2, 3, 5 }, M
7 min read
Maximum subset sum having difference between its maximum and minimum in range [L, R]
Given an array arr[] of N positive integers and a range [L, R], the task is to find the maximum subset-sum such that the difference between the maximum and minimum elements of the subset lies in the given range. Examples: Input: arr[] = {6, 5, 0, 9, 1}, L = 0, R = 3Output: 15Explanation: The subset {6, 9} of the given array has the difference betwe
9 min read
Subset with sum closest to zero
Given an array 'arr' consisting of integers, the task is to find the non-empty subset such that its sum is closest to zero i.e. absolute difference between zero and the sum is minimum.Examples: Input : arr[] = {2, 2, 2, -4} Output : 0 arr[0] + arr[1] + arr[3] = 0 That's why answer is zero.Input : arr[] = {1, 1, 1, 1} Output : 1 One simple approach
8 min read
Maximum subset sum such that no two elements in set have same digit in them
Given an array of N elements. Find the subset of elements which has maximum sum such that no two elements in the subset has common digit present in them.Examples: Input : array[] = {22, 132, 4, 45, 12, 223} Output : 268 Maximum Sum Subset will be = {45, 223} . All possible digits are present except 1. But to include 1 either 2 or both 2 and 3 have
12 min read
Sum of all subset sums of a linked list
Given a linked list, the task is to find the sum of all subsets of a linked list.Examples: Input: 2 -> 3 -> NULL Output: 10 Explanation: All non-empty subsets are {2}, {3} and {2, 3} Total sum = 2 + 3 + (2 + 3) = 10Input: 2 -> 1 -> 5 -> 6 -> NULL Output: 112 Approach: Considering all the possible subsets, we can observe that each
6 min read
Maximum sum subset having equal number of positive and negative elements
Given an array arr[], the task is to find the maximum sum subset containing the equal number of positive and negative elements. Examples: Input: arr[] = {1, -2, 3, 4, -5, 8} Output: 6 Explanation: Maximum sum subset with equal number of positive and negative elements {8, -2} Input: arr[] = {-1, -2, -3, -4, -5} Output: 0 Explanation: As there are no
7 min read
Find subset with maximum sum under given condition
Given values[] and labels[] of n items and a positive integer limit, We need to choose a subset of these items in such a way that the number of the same type of label in the subset should be <= limit and sum of values are maximum among all possible subset choices. Examples: Input: values[] = [5, 3, 7, 1, 2], labels[] = [5, 7, 7, 7, 6], limit = 2
6 min read
Maximum size subset with given sum using Backtracking
Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subsequence with a sum equal to K.Examples: Input: arr[] = {-4, -2, -2, -1, 6}, K = 0 Output: 3 Explanation: The longest subsequence is of length 3 which is {-4, -2, 6} having sum 0.Input: arr[] = {-3, 0, 1, 1, 2}, K = 1 Output: 5 Explanati
9 min read
Largest subset with composite sum in given Array
Given an array arr[] consisting of n distinct positive integers. Find the length of the largest subset in the given array which sums to a composite number and print the required array(order or printing elements does not matter). Note: In case of multiple subsets with this largest size with the composite sum, output any of them. Examples: Input: arr
10 min read