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

C Program for Subset Sum Problem | DP-25

Last Updated : 09 Nov, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Write a C program for a given 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 adds up to 30.

C Program for 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.

Step-by-step approach:

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


Output

Found a subset with given sum

Time Complexity: O(2n)
Auxiliary space: O(n)

C Program for 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




#include <stdio.h>
#include <string.h>
 
// Taking the matrix as globally
int tab[2000][2000];
 
// Check if a possible subset with
// the 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 called the function
    // with the same value.
    // It will save us from 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 fulfills our criteria.
        // That's why we're doing two calls
        return tab[n - 1][sum] = subsetSum(a, n - 1, sum) ||
                                subsetSum(a, n - 1, sum - a[n - 1]);
    }
}
 
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)) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
 
    return 0;
}


Output

YES

Time Complexity: O(sum*n)
Auxiliary space: O(n)

C Program for Subset Sum Problem using Dynamic Programming:

We can 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]]

Below is the implementation of the above approach:

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.


Output

Found a subset with given sum

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.

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

In previous approach of dynamic programming we have derive the relation between states as given below:
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]]
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-set[i-1]].
There is no need to store all the previous states just one previous state is used to compute result.

Step-by-step 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.

Below is the implementation of the above approach:

C




#include <stdio.h>
#include <stdbool.h>
 
// Returns true if there is a subset of set[]
// with a sum equal to the given sum
bool isSubsetSum(int set[], int n, int sum) {
    bool prev[sum + 1];
 
    // If sum is 0, then the answer is true
    for (int i = 0; i <= n; i++)
        prev[0] = true;
 
    // If sum is not 0 and set is empty,
    // then the answer is false
    for (int i = 1; i <= sum; i++)
        prev[i] = false;
 
    // curr array to store the current row result generated
    // with the help of the prev array
    bool curr[sum + 1];
 
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= sum; j++) {
            if (j < set[i - 1])
                curr[j] = prev[j];
            if (j >= set[i - 1])
                curr[j] = prev[j] || prev[j - set[i - 1]];
        }
        // now curr becomes prev for the (i + 1)-th element
        for (int j = 0; j <= sum; j++)
            prev[j] = curr[j];
    }
 
    return prev[sum];
}
 
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)) {
        printf("Found a subset with given sum\n");
    } else {
        printf("No subset with given sum\n");
    }
 
    return 0;
}


Output

Found a subset with given sum

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.

Please refer complete article on Subset Sum Problem | DP-25 for more details!



Previous Article
Next Article

Similar Reads

C / C++ Program for Subset Sum | Backtracking-4
Write a C/C++ program for a given 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. 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
3 min read
C Program for Number of stopping station problem
There are 12 intermediate stations between two places A and B. Find the number of ways in which a train can be made to stop at 4 of these intermediate stations so that no two stopping stations are consecutive? Examples - Input : n = 12, s = 4 Output : 126 Input : n = 16, s = 5 Output : 792 #include &lt;stdio.h&gt; int stopping_station(int, int); //
2 min read
C Program for Activity Selection Problem | Greedy Algo-1
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Example: Example 1 : Consider the following 3 activities sorted by finish time. start[] = {10, 12, 20}; finish[] = {20, 25, 30}; A person
2 min read
C Program for N Queen Problem | Backtracking-3
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, the following is the output matrix for above 4 queen solution. { 0,
3 min read
C Program to Solve the 0-1 Knapsack Problem
Prerequisite: Introduction to Knapsack Problem, its Types and How to solve them The 0-1 Knapsack Problem is a classic dynamic programming problem where the goal is to maximize the total value of ( N ) items, each having a weight and a value, that can be included in a knapsack with a maximum weight capacity ( W ) without exceeding its capacity. It d
8 min read
Producer Consumer Problem in C
Concurrency is an important topic in concurrent programming since it allows us to completely understand how the systems work. Among the several challenges faced by practitioners working with these systems, there is a major synchronization issue which is the producer-consumer problem. In this article, we will discuss this problem and look at possibl
5 min read
C Program for Sum the digits of a given number
Given a number, find sum of its digits.Example : Input : n = 687 Output : 21 Input : n = 12 Output : 3 1. Iterative: C/C++ Code // C program to compute sum of digits in // number. # include&lt;stdio.h&gt; /* Function to get sum of digits */ int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } int main() {
1 min read
C/C++ Program to Find sum of Series with n-th term as n^2 - (n-1)^2
We are given an integer n and n-th term in a series as expressed below: Tn = n2 - (n-1)2 We need to find Sn mod (109 + 7), where Sn is the sum of all of the terms of the given series and, Sn = T1 + T2 + T3 + T4 + ...... + Tn Examples: Input : 229137999 Output : 218194447 Input : 344936985 Output : 788019571 Let us do some calculations, before writi
2 min read
Program For Finding A Triplet From Three Linked Lists With Sum Equal To A Given Number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12-&gt;6-&gt;29, 23-&gt;5-&gt;8, and 90-&gt;20-&gt;59, and the given number is 101, the output should be triple "6 5 90".In the following solutions, size of all th
11 min read
C Program For Finding A Triplet From Three Linked Lists With Sum Equal To A Given Number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12-&gt;6-&gt;29, 23-&gt;5-&gt;8, and 90-&gt;20-&gt;59, and the given number is 101, the output should be triple "6 5 90".In the following solutions, size of all th
4 min read
Article Tags :
three90RightbarBannerImg