Perfect Sum Problem

21 Dec, 2021
Given an array arr[] of integers and an integer K, the task is to print all subsets of the given array with the sum equal to the given target K.Examples:  
Input: arr[] = {5, 10, 12, 13, 15, 18}, K = 30
Output: {12, 18}, {5, 12, 13}, {5, 10, 15}
Explanation: 
Subsets with sum 30 are:
12 + 18 = 30
5 + 12 + 13 = 30
5 + 10 + 15 = 30

Input: arr[] = {1, 2, 3, 4}, K = 5
Output: {2, 3}, {1, 4}
 
Approach: The idea is to find out all the subsets using the Power Set concept. For every set, check if the sum of the set is equal to K or not. If it is equal, then the set is printed. Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; // Function to print the subsets whose// sum is equal to the given target Kvoid sumSubsets(vector<int> set, int n, int target){    // Create the new array with size    // equal to array set[] to create    // binary array as per n(decimal number)    int x[set.size()];    int j = set.size() - 1;     // Convert the array into binary array    while (n > 0)    {        x[j] = n % 2;        n = n / 2;        j--;    }     int sum = 0;     // Calculate the sum of this subset    for (int i = 0; i < set.size(); i++)        if (x[i] == 1)            sum = sum + set[i];     // Check whether sum is equal to target    // if it is equal, then print the subset    if (sum == target)    {        cout<<("{");        for (int i = 0; i < set.size(); i++)            if (x[i] == 1)                cout << set[i] << ", ";        cout << ("}, ");    }} // Function to find the subsets with sum Kvoid findSubsets(vector<int> arr, int K){    // Calculate the total no. of subsets    int x = pow(2, arr.size());     // Run loop till total no. of subsets    // and call the function for each subset    for (int i = 1; i < x; i++)        sumSubsets(arr, i, K);} // Driver codeint main(){    vector<int> arr = { 5, 10, 12, 13, 15, 18 };    int K = 30;    findSubsets(arr, K);    return 0;} // This code is contributed by mohit kumar 29
// Java implementation of the above approachimport java.util.*; class GFG {     // Function to print the subsets whose    // sum is equal to the given target K    public static void sumSubsets(        int set[], int n, int target)    {        // Create the new array with size        // equal to array set[] to create        // binary array as per n(decimal number)        int x[] = new int[set.length];        int j = set.length - 1;         // Convert the array into binary array        while (n > 0) {            x[j] = n % 2;            n = n / 2;            j--;        }         int sum = 0;         // Calculate the sum of this subset        for (int i = 0; i < set.length; i++)            if (x[i] == 1)                sum = sum + set[i];         // Check whether sum is equal to target        // if it is equal, then print the subset        if (sum == target) {            System.out.print("{");            for (int i = 0; i < set.length; i++)                if (x[i] == 1)                    System.out.print(set[i] + ", ");            System.out.print("}, ");        }    }     // Function to find the subsets with sum K    public static void findSubsets(int[] arr, int K)    {        // Calculate the total no. of subsets        int x = (int)Math.pow(2, arr.length);         // Run loop till total no. of subsets        // and call the function for each subset        for (int i = 1; i < x; i++)            sumSubsets(arr, i, K);    }     // Driver code    public static void main(String args[])    {        int arr[] = { 5, 10, 12, 13, 15, 18 };        int K = 30;         findSubsets(arr, K);    }}
# Python3 implementation of the above approach # Function to print the subsets whose# sum is equal to the given target Kdef sumSubsets(sets, n, target) :     # Create the new array with size    # equal to array set[] to create    # binary array as per n(decimal number)    x = [0]*len(sets);    j = len(sets) - 1;     # Convert the array into binary array    while (n > 0) :             x[j] = n % 2;        n = n // 2;        j -= 1;         sum = 0;     # Calculate the sum of this subset    for i in range(len(sets)) :        if (x[i] == 1) :            sum += sets[i];     # Check whether sum is equal to target    # if it is equal, then print the subset    if (sum == target) :         print("{",end="");        for i in range(len(sets)) :            if (x[i] == 1) :                print(sets[i],end= ", ");        print("}, ",end=""); # Function to find the subsets with sum Kdef findSubsets(arr, K) :     # Calculate the total no. of subsets    x = pow(2, len(arr));     # Run loop till total no. of subsets    # and call the function for each subset    for i in range(1, x) :        sumSubsets(arr, i, K); # Driver codeif __name__ == "__main__" :     arr = [ 5, 10, 12, 13, 15, 18 ];    K = 30;    findSubsets(arr, K); # This code is contributed by Yash_R
// C# implementation of the above approachusing System; class GFG{     // Function to print the subsets whose    // sum is equal to the given target K    public static void sumSubsets(        int []set, int n, int target)    {        // Create the new array with size        // equal to array set[] to create        // binary array as per n(decimal number)        int []x = new int[set.Length];        int j = set.Length - 1;         // Convert the array into binary array        while (n > 0)        {            x[j] = n % 2;            n = n / 2;            j--;        }         int sum = 0;         // Calculate the sum of this subset        for (int i = 0; i < set.Length; i++)            if (x[i] == 1)                sum = sum + set[i];         // Check whether sum is equal to target        // if it is equal, then print the subset        if (sum == target)        {            Console.Write("{");            for (int i = 0; i < set.Length; i++)                if (x[i] == 1)                    Console.Write(set[i] + ", ");            Console.Write("}, ");        }    }     // Function to find the subsets with sum K    public static void findSubsets(int[] arr, int K)    {        // Calculate the total no. of subsets        int x = (int)Math.Pow(2, arr.Length);         // Run loop till total no. of subsets        // and call the function for each subset        for (int i = 1; i < x; i++)            sumSubsets(arr, i, K);    }     // Driver code    public static void Main(String []args)    {        int []arr = { 5, 10, 12, 13, 15, 18 };        int K = 30;         findSubsets(arr, K);    }} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the above approach  // Function to print the subsets whose// sum is equal to the given target Kfunction sumSubsets(set, n, target) {    // Create the new array with length    // equal to array set[] to create    // binary array as per n(decimal number)    let x = new Array(set.length);    let j = set.length - 1;     // Convert the array into binary array    while (n > 0) {        x[j] = n % 2;        n = Math.floor(n / 2);        j--;    }     let sum = 0;     // Calculate the sum of this subset    for (let i = 0; i < set.length; i++)        if (x[i] == 1)            sum = sum + set[i];     // Check whether sum is equal to target    // if it is equal, then print the subset    if (sum == target) {        document.write("{");        for (let i = 0; i < set.length; i++)            if (x[i] == 1)                document.write(set[i] + ", ");        document.write("}, ");    }} // Function to find the subsets with sum Kfunction findSubsets(arr, K) {    // Calculate the total no. of subsets    let x = Math.pow(2, arr.length);     // Run loop till total no. of subsets    // and call the function for each subset    for (let i = 1; i < x; i++)        sumSubsets(arr, i, K);} // Driver code let arr = [5, 10, 12, 13, 15, 18];let K = 30;findSubsets(arr, K);  // This code is contributed by gfgking </script>
{12, 18, }, {5, 12, 13, }, {5, 10, 15, },
 
Time Complexity: 2N
Auxiliary Space: O(N)Efficient Approach: This problem can also be solved using Dynamic Programming. Refer to this article. 
mohit kumar 29
29AjayKumar
Yash_R
gfgking
vansikasharma1329
subset
Arrays
Backtracking
Mathematical
Arrays
Mathematical
subset
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
N Queen Problem | Backtracking-3
Backtracking | Introduction
Rat in a Maze | Backtracking-2
The Knight's tour problem | Backtracking-1