Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Number of K length subsequences with minimum sum
Next article icon

Unique subsequences of length K with given sum

Last Updated : 02 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N integers and two numbers K and S, the task is to print all the subsequence of length K with the sum S.
Examples: 
 

Input: N = 5, K = 3, S = 20, arr[] = {4, 6, 8, 2, 12} 
Output: 
{6, 2, 12} 
Explanation: 
Only one subsequence of size 3 with a sum 20 is possible i.e., {6, 2, 12} and sum is 6 + 2 + 12 = 20
Input: N = 10, K = 5, S = 25, arr[] = {2, 4, 6, 8, 10, 12, 1, 2, 5, 7} 
Output: 
{10, 1, 2, 5, 7} 
{4, 8, 1, 5, 7} 
{4, 8, 10, 1, 2} 
{4, 6, 12, 1, 2} 
{4, 6, 8, 2, 5} 
{2, 10, 1, 5, 7} 
{2, 8, 12, 1, 2} 
{2, 6, 10, 2, 5} 
{2, 6, 8, 2, 7} 
{2, 4, 12, 2, 5} 
{2, 4, 10, 2, 7} 
{2, 4, 8, 10, 1} 
{2, 4, 6, 12, 1} 
{2, 4, 6, 8, 5} 
 

 

Approach: The idea is to use Backtracking to print all the subsequence with given sum S. Below are the steps: 
 

  • Iterate for all the value of the array arr[] and do the following: 
    1. If we include the current element in the resultant subsequence then, decrement K and the above value of current element to the sum S.
    2. Recursively iterate from next index of the element to the end of the array to find the resultant subsequence.
    3. If K is 0 and S is 0 then we got our one of the resultant subsequence of length K and sum S, print this subsequence and backtrack for the next resulting subsequence.
    4. If we doesn’t include the current element then, find the resultant subsequence by excluding the current element and repeating the above procedure for the rest of the element in the array.
  • Resultant array in the steps 3 will give all the possible subsequence of length K with given sum S.

Below is the implementation of the above approach: 
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find all the subsequences
// of a given length and having sum S
void comb(int* arr, int len, int r,
          int ipos, int* op, int opos,
          int sum)
{
 
    // Termination condition
    if (opos == r) {
 
        int sum2 = 0;
        for (int i = 0; i < opos; i++) {
 
            // Add value to sum
            sum2 = sum2 + op[i];
        }
 
        // Check if the resultant sum
        // equals to target sum
        if (sum == sum2) {
 
            // If true
            for (int i = 0; i < opos; i++)
 
                // Print resultant array
                cout << op[i] << ", ";
 
            cout << endl;
        }
 
        // End this recursion stack
        return;
    }
    if (ipos < len) {
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos, sum);
 
        op[opos] = arr[ipos];
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos + 1, sum);
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 4, 6, 8, 2, 12 };
    int K = 3;
    int S = 20;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // To store the subsequence
    int op[N] = { 0 };
 
    // Function Call
    comb(arr, N, K, 0, op, 0, S);
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find all the subsequences
// of a given length and having sum S
static void comb(int []arr, int len, int r,
                 int ipos, int[] op, int opos,
                 int sum)
{
 
    // Termination condition
    if (opos == r)
    {
        int sum2 = 0;
        for(int i = 0; i < opos; i++)
        {
             
           // Add value to sum
           sum2 = sum2 + op[i];
        }
 
        // Check if the resultant sum
        // equals to target sum
        if (sum == sum2)
        {
 
            // If true
            for(int i = 0; i < opos; i++)
                
               // Print resultant array
               System.out.print(op[i] + ", ");
 
            System.out.println();
        }
 
        // End this recursion stack
        return;
    }
    if (ipos < len)
    {
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos, sum);
              
        op[opos] = arr[ipos];
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos + 1, sum);
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array
    int arr[] = { 4, 6, 8, 2, 12 };
    int K = 3;
    int S = 20;
 
    int N = arr.length;
 
    // To store the subsequence
    int op[] = new int[N];
 
    // Function Call
    comb(arr, N, K, 0, op, 0, S);
}
}
 
// This code is contributed by amal kumar choubey
 
 

Python3




# Python3 program for the above approach
 
# Function to find all the subsequences
# of a given length and having sum S
def comb(arr, Len, r, ipos, op, opos, Sum):
 
    # Termination condition
    if (opos == r):
 
        sum2 = 0
        for i in range(opos):
 
            # Add value to sum
            sum2 = sum2 + op[i]
 
        # Check if the resultant sum
        # equals to target sum
        if (Sum == sum2):
 
            # If true
            for i in range(opos):
 
                # Print resultant array
                print(op[i], end = ", ")
 
            print()
 
        # End this recursion stack
        return
 
    if (ipos < Len):
 
        # Check all the combinations
        # using backtracking
        comb(arr, Len, r, ipos + 1,
             op, opos, Sum)
 
        op[opos] = arr[ipos]
 
        # Check all the combinations
        # using backtracking
        comb(arr, Len, r, ipos + 1, op,
                          opos + 1, Sum)
 
# Driver code
if __name__ == '__main__':
 
    # Given array
    arr = [ 4, 6, 8, 2, 12 ]
    K = 3
    S = 20
    N = len(arr)
 
    # To store the subsequence
    op = [0] * N
 
    # Function call
    comb(arr, N, K, 0, op, 0, S)
 
# This code is contributed by himanshu77
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find all the subsequences
// of a given length and having sum S
static void comb(int []arr, int len, int r,
                 int ipos, int[] op, int opos,
                 int sum)
{
 
    // Termination condition
    if (opos == r)
    {
        int sum2 = 0;
        for(int i = 0; i < opos; i++)
        {
            
           // Add value to sum
           sum2 = sum2 + op[i];
        }
 
        // Check if the resultant sum
        // equals to target sum
        if (sum == sum2)
        {
 
            // If true
            for(int i = 0; i < opos; i++)
                
               // Print resultant array
               Console.Write(op[i] + ", ");
            Console.WriteLine();
        }
 
        // End this recursion stack
        return;
    }
    if (ipos < len)
    {
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos, sum);
             
        op[opos] = arr[ipos];
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos + 1, sum);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []arr = { 4, 6, 8, 2, 12 };
    int K = 3;
    int S = 20;
 
    int N = arr.Length;
 
    // To store the subsequence
    int []op = new int[N];
 
    // Function call
    comb(arr, N, K, 0, op, 0, S);
}
}
 
// This code is contributed by amal kumar choubey
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find all the subsequences
// of a given length and having sum S
function comb(arr, len, r,
                 ipos, op, opos,
                 sum)
{
 
    // Termination condition
    if (opos == r)
    {
        let sum2 = 0;
        for(let i = 0; i < opos; i++)
        {
             
           // Add value to sum
           sum2 = sum2 + op[i];
        }
 
        // Check if the resultant sum
        // equals to target sum
        if (sum == sum2)
        {
 
            // If true
            for(let i = 0; i < opos; i++)
                
               // Print resultant array
               document.write(op[i] + ", ");
 
            document.write();
        }
 
        // End this recursion stack
        return;
    }
    if (ipos < len)
    {
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos, sum);
              
        op[opos] = arr[ipos];
 
        // Check all the combinations
        // using backtracking
        comb(arr, len, r, ipos + 1,
             op, opos + 1, sum);
    }
}
  
// Driver Code
 
    // Given array
    let arr = [ 4, 6, 8, 2, 12 ];
    let K = 3;
    let S = 20;
 
    let N = arr.length;
 
    // To store the subsequence
    let op = Array.from({length: N}, (_, i) => 0);
 
    // Function Call
    comb(arr, N, K, 0, op, 0, S);
 
// This code is contributed by sanjoy_62.
</script>
 
 

Output: 
 

6, 2, 12, 

Time Complexity: O(2^N * K)  
Auxiliary Space: O(N)



Next Article
Number of K length subsequences with minimum sum

M

manavgoswami001
Improve
Article Tags :
  • Algorithms
  • Arrays
  • Articles
  • Backtracking
  • C++
  • C/C++ Puzzles
  • Competitive Programming
  • CS - Placements
  • Data Structures
  • DSA
  • Programming Language
  • Stack
  • Algorithms-Backtracking
  • subsequence
Practice Tags :
  • CPP
  • Algorithms
  • Arrays
  • Backtracking
  • Data Structures
  • Stack

Similar Reads

  • Length of Longest Common Subsequence with given sum K
    Given two arrays a[] and b[] and an integer K, the task is to find the length of the longest common subsequence such that sum of elements is equal to K. Examples: Input: a[] = { 9, 11, 2, 1, 6, 2, 7}, b[] = {1, 2, 6, 9, 2, 3, 11, 7}, K = 18Output: 3Explanation: Subsequence { 11, 7 } and { 9, 2, 7 }
    15+ min read
  • Sum of all subsequences of length K
    Given an array arr[]and an integer K, the task is to find the sum of all K length subsequences from the given array. Example: Input: arr[] = {2, 3, 4}, K = 2 Output: 18 Explanation: There are 3 possible subsequences of length 2 which are {2, 3}, {2, 4} and {3, 4} The sum of all 2 length subsequences
    6 min read
  • Count of unique Subsequences of given String with lengths in range [0, N]
    Given a string S of length N, the task is to find the number of unique subsequences of the string for each length from 0 to N. Note: The uppercase letters and lowercase letters are considered different and the result may be large so print it modulo 1000000007. Examples: Input: S = "ababd"Output: Num
    15 min read
  • Number of K length subsequences with minimum sum
    Given an array arr[] of size N and an integer K, the task is to find the number of K length subsequences of this array such that the sum of these subsequences is the minimum possible. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 1 Subsequences of length 2 are (1, 2), (1, 3), (1, 4), (2, 3),
    8 min read
  • Longest Subarray with K Sections of Unique Items
    You are given an array of positive integers arr[] and an integer k. The task is to find length of the longest subarray with the following conditions Each element must fit into one of k sections. Each section can only store a unique number and its multiple consecutive instances.Examples: Input: arr[]
    7 min read
  • Maximum Sum Subsequence of length k
    Given an array sequence [A1, A2 ...An], the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3.........<=Sk. Examples: Input : n = 8 k = 3 A=[8 5 9 10 5 6 21 8] Output : 40 Possible Increasing subsequence of Length 3 with maximum possible s
    11 min read
  • Number of Subsequences with Even and Odd Sum
    Given an array, find the number of subsequences whose sum is even and the number of subsequences whose sum is odd. Example: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are [Tex]2^{N}-1 [/Tex]possible subsequences. The subsequences with even sum is 1) {1, 3} Sum = 4 2) {1, 2, 2,
    15 min read
  • Number of subsequences with zero sum
    Given an array arr[] of N integers. The task is to count the number of sub-sequences whose sum is 0. Examples: Input: arr[] = {-1, 2, -2, 1} Output: 3 All possible sub-sequences are {-1, 1}, {2, -2} and {-1, 2, -2, 1} Input: arr[] = {-2, -4, -1, 6, -2} Output: 2 Approach: The problem can be solved u
    6 min read
  • Shortest Subsequence with sum exactly K
    Given an array Arr[] of size N and an integer K, the task is to find the length of the shortest subsequence having sum exactly K. Examples: Input: N = 5, K = 4, Arr[] = {1, 2, 2, 3, 4}Output: 1Explanation: Here, one can choose the last month and can get 4 working hours. Input: N = 3, K = 2, Arr[] =
    15+ min read
  • Maximum sum subsequence of length K | Set 2
    Given an array sequence arr[] i.e [A1, A2 …An] and an integer k, the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3………<=Sk. Examples: Input: arr[] = {-1, 3, 4, 2, 5}, K = 3Output: 3 4 5Explanation: Subsequence 3 4 5 with sum 12 is the s
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences