# Find all subsequences with sum equals to K

Given an array arr[] of length N and a number K, the task is to find all the subsequences of the array whose sum of elements is K

Examples:

Input: arr[] = {1, 2, 3}, K = 3
Output:
1 2
3

Input: arr[] = {17, 18, 6, 11, 2, 4}, K = 6
Output:
2 4
6

Approach:
The idea is to use the jagged array to store the subsequences of the array of different lengths. For every element in the array, there are mainly two choices for it that are either to include in the subsequence or not. Apply this for every element in the array by reducing the sum, if the element is included otherwise search for the subsequence without including it.

Below is the implementation of the above approach:

## C++

 `// C++ implementation to find all the``// subsequence whose sum is K` `#include ``using` `namespace` `std;` `// Utility function to find the subsequences``// whose sum of the element is K``int` `subsetSumToK(``int` `arr[], ``int` `n,``            ``int` `output[][50], ``int` `k){``    ` `    ``// Base Case``    ``if` `(n == 0) {``        ``if` `(k == 0) {``            ``output[0][0] = 0;``            ``return` `1;``        ``}``        ``else` `{``            ``return` `0;``        ``}``    ``}``    ` `    ``// Array to store the subsequences ``    ``// which includes the element arr[0]``    ``int` `output1[1000][50]; ``    ` `    ``// Array to store the subsequences ``    ``// which not includes the element arr[0]``    ``int` `output2[1000][50];``    ` `    ``// Recursive call to find the subsequences``    ``// which includes the element arr[0]``    ``int` `size1 = subsetSumToK(arr + 1,``        ``n - 1, output1, k - arr[0]);``    ` `    ``// Recursive call to find the subsequences``    ``// which not includes the element arr[0]``    ``int` `size2 = subsetSumToK(arr + 1, n - 1,``                                ``output2, k);` `    ``int` `i, j;``    ` `    ``// Loop to update the results of the ``    ``// Recursive call of the function``    ``for` `(i = 0; i < size1; i++) {``        ` `        ``// Incrementing the length of ``        ``// jagged array because it includes``        ``// the arr[0] element of the array``        ``output[i][0] = output1[i][0] + 1;``        ` `        ``// In the first column of the jagged``        ``// array put the arr[0] element``        ``output[i][1] = arr[0];``    ``}``    ` `    ``// Loop to update the subsequence ``    ``// in the output array``    ``for` `(i = 0; i < size1; i++) {``        ``for` `(j = 1; j <= output1[i][0]; j++) {``            ``output[i][j + 1] = output1[i][j];``        ``}``    ``}``    ` `    ``// Loop to update the subsequences ``    ``// which do not include the arr[0] element``    ``for` `(i = 0; i < size2; i++) {``        ``for` `(j = 0; j <= output2[i][0]; j++) {``            ``output[i + size1][j] = output2[i][j];``        ``}``    ``}``    ` `    ``return` `size1 + size2;``}` `// Function to find the subsequences``// whose sum of the element is K``void` `countSubsequences(``int` `arr[], ``int` `n,``            ``int` `output[][50], ``int` `k)``{   ``    ``int` `size = subsetSumToK(arr, n, output, k);``    ` `    ``for` `(``int` `i = 0; i < size; i++) {``        ``for` `(``int` `j = 1; j <= output[i][0]; j++) {``            ``cout << output[i][j] << ``" "``;``        ``}``        ``cout << endl;``    ``}    ``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = {5, 12, 3, 17, 1, 18, 15, 3, 17};``    ``int` `length = 9, output[1000][50], k = 6;` `    ``countSubsequences(arr, length, output, k);` `    ``return` `0;``}`

## Java

 `// Java implementation to find all the``// sub-sequences whose sum is K` `import` `java.util.*;``public` `class` `SubsequenceSumK {` `    ``// Function to find the subsequences``    ``// with given sum``    ``public` `static` `void` `subSequenceSum(``        ``ArrayList> ans, ``        ``int` `a[], ArrayList temp, ``                        ``int` `k, ``int` `start)``    ``{``        ``// Here we have used ArrayList``        ``// of ArrayList in Java for ``        ``// implementation of Jagged Array` `        ``// if k < 0 then the sum of``        ``// the current subsequence``        ``// in temp is greater than K``        ``if``(start > a.length || k < ``0``)``            ``return` `;` `        ``// if(k==0) means that the sum ``        ``// of this subsequence``        ``// is equal to K``        ``if``(k == ``0``)``        ``{``            ``ans.add(``             ``new` `ArrayList(temp)``             ``);``            ``return` `;``        ``}``        ``else` `{``            ``for` `(``int` `i = start; ``                 ``i < a.length; i++) {` `                ``// Adding a new ``                ``// element into temp``                ``temp.add(a[i]);` `                ``// After selecting an``                ``// element from the``                ``// array we subtract K``                ``// by that value``                ``subSequenceSum(ans, a, ``                   ``temp, k - a[i],i+``1``);` `                ``// Remove the lastly ``                ``// added element``                ``temp.remove(temp.size() - ``1``);``            ``}``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `arr[] = {``5``, ``12``, ``3``, ``17``, ``1``, ``                     ``18``, ``15``, ``3``, ``17``};``        ``int` `k = ``6``;``        ``ArrayList> ans;``        ``ans= ``new` `ArrayList<``                  ``ArrayList>();``        ``subSequenceSum(ans, arr, ``            ``new` `ArrayList(), k, ``0``);``            ` `        ``// Loop to print the subsequences``        ``for``(``int` `i = ``0``; i < ans.size(); ``         ``i++){``            ``for``(``int` `j = ``0``; ``              ``j < ans.get(i).size(); j++){``                ``System.out.print(``                    ``ans.get(i).get(j));``                ``System.out.print(``" "``);``            ``}``            ``System.out.println();``        ``}``    ``}``}`

## Python3

 `# Python3 implementation to find all the``# subsequence whose sum is K`` ` `# Utility function to find the subsequences``# whose sum of the element is K``def` `subsetSumToK(arr, n, output, k):``     ` `    ``# Base Case``    ``if` `(n ``=``=` `0``):``        ``if` `(k ``=``=` `0``):``            ``output[``0``][``0``] ``=` `0``;``            ``return` `1``;``        ``else``:``            ``return` `0``;``     ` `    ``# Array to store the subsequences ``    ``# which includes the element arr[0]    ``    ``output1 ``=` `[[``0` `for` `j ``in` `range``(``50``)] ``for` `i ``in` `range``(``1000``)]``     ` `    ``# Array to store the subsequences ``    ``# which not includes the element arr[0]``    ``output2 ``=` `[[``0` `for` `j ``in` `range``(``50``)] ``for` `i ``in` `range``(``1000``)]``     ` `    ``# Recursive call to find the subsequences``    ``# which includes the element arr[0]``    ``size1 ``=` `subsetSumToK(arr[``1``:], n ``-` `1``, output1, k ``-` `arr[``0``]);``     ` `    ``# Recursive call to find the subsequences``    ``# which not includes the element arr[0]``    ``size2 ``=` `subsetSumToK(arr[``1``:], n ``-` `1``, output2, k)``     ` `    ``# Loop to update the results of the ``    ``# Recursive call of the function``    ``for` `i ``in` `range``(size1):``         ` `        ``# Incrementing the length of ``        ``# jagged array because it includes``        ``# the arr[0] element of the array``        ``output[i][``0``] ``=` `output1[i][``0``] ``+` `1``;``         ` `        ``# In the first column of the jagged``        ``# array put the arr[0] element``        ``output[i][``1``] ``=` `arr[``0``];``     ` `    ``# Loop to update the subsequence ``    ``# in the output array``    ``for` `i ``in` `range``(size1):``        ``for` `j ``in` `range``(``1``, output1[i][``0``]``+``1``):   ``            ``output[i][j ``+` `1``] ``=` `output1[i][j];``     ` `    ``# Loop to update the subsequences ``    ``# which do not include the arr[0] element``    ``for` `i ``in` `range``(size2):``        ``for` `j ``in` `range``(output2[i][``0``] ``+` `1``):``            ``output[i ``+` `size1][j] ``=` `output2[i][j];``     ` `    ``return` `size1 ``+` `size2;` `# Function to find the subsequences``# whose sum of the element is K``def` `countSubsequences(arr, n, output, k):``    ``size ``=` `subsetSumToK(arr, n, output, k);``    ``for` `i ``in` `range``(size):     ``        ``for` `j ``in` `range``(``1``, output[i][``0``] ``+` `1``):``            ``print``(output[i][j], end ``=` `' '``)``        ``print``()``        ` `# Driver Code``if` `__name__``=``=``'__main__'``:` `    ``arr ``=` `[``5``, ``12``, ``3``, ``17``, ``1``, ``18``, ``15``, ``3``, ``17``]``    ``length ``=` `9``    ``output ``=` `[[``0` `for` `j ``in` `range``(``50``)] ``for` `i ``in` `range``(``1000``)]``    ``k ``=` `6``;`` ` `    ``countSubsequences(arr, length, output, k);` `  ``# This code is contributed by rutvik_56.`

## C#

 `// C# implementation to find all the ``// subsequence whose sum is K ``using` `System;``using` `System.Collections;``using` `System.Collections.Generic;` `class` `GFG{``    ` `// Function to find the subsequences ``// with given sum ``public` `static` `void` `subSequenceSum( ``    ``List> ans, ``int``[] a,``    ``List<``int``> temp, ``int` `k, ``int` `start) ``{ ``    ` `    ``// Here we have used ArrayList ``    ``// of ArrayList in Java for  ``    ``// implementation of Jagged Array ` `    ``// If k < 0 then the sum of ``    ``// the current subsequence ``    ``// in temp is greater than K ``    ``if` `(start > a.Length || k < 0) ``        ``return``; ` `    ``// If (k==0) means that the sum  ``    ``// of this subsequence ``    ``// is equal to K ``    ``if` `(k == 0) ``    ``{ ``        ``ans.Add(``new` `List<``int``>(temp)); ``        ``return``; ``    ``} ``    ``else``    ``{ ``        ``for``(``int` `i = start; ``                ``i < a.Length; i++) ``        ``{ ``            ` `            ``// Adding a new  ``            ``// element into temp ``            ``temp.Add(a[i]); ` `            ``// After selecting an ``            ``// element from the ``            ``// array we subtract K ``            ``// by that value ``            ``subSequenceSum(ans, a,  ``               ``temp, k - a[i], i + 1); ` `            ``// Remove the lastly  ``            ``// added element ``            ``temp.RemoveAt(temp.Count - 1); ``        ``} ``    ``} ``} ` `// Driver code ``static` `public` `void` `Main ()``{``    ``int``[] arr = { 5, 12, 3, 17, 1, ``                  ``18, 15, 3, 17 }; ``    ``int` `k = 6; ``    ` `    ``List> ans = ``new` `List>(); ``    ` `    ``subSequenceSum(ans, arr, ``    ``new` `List<``int``>(), k, 0); ``    ` `    ``// Loop to print the subsequences ``    ``for``(``int` `i = 0; i < ans.Count; i++)``    ``{ ``        ``for``(``int` `j = 0; j < ans[i].Count; j++)``        ``{ ``            ``Console.Write(ans[i][j] + ``" "``); ``        ``} ``        ``Console.WriteLine(); ``    ``}  ``}``}` `// This code is contributed by offbeat`

## Javascript

 ``

Output:
```5 1
3 3```

Time Complexity: O(2^n)

As we have to generate all the subsequences in the worst case.

Auxiliary Space: O(h)

Here h is height of the tree and the extra space is used due to recursive function call stack. If we exclude the space used to store the result.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next