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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print all subsets with given sum
Next article icon

Recursive program to print all subsets with given sum

Last Updated : 12 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array and a number, print all subsets with sum equal to given the sum.
Examples: 
 

Input :  arr[] =  {2, 5, 8, 4, 6, 11}, sum = 13 Output :  5 8 2 11 2 5 6  Input : arr[] =  {1, 5, 8, 4, 6, 11}, sum = 9 Output : 5 4 1 8

 

This problem is an extension of check if there is a subset with given sum. We recursively generate all subsets. We keep track of elements of current subset. If sum of elements in current subset becomes equal to given sum, we print the subset. 
 

C++




// CPP program to print all subsets with given sum
#include <bits/stdc++.h>
using namespace std;
 
// The vector v stores current subset.
void printAllSubsetsRec(int arr[], int n, vector<int> v,
                        int sum)
{
    // If remaining sum is 0, then print all
    // elements of current subset.
    if (sum == 0) {
        for (auto x : v)
            cout << x << " ";
        cout << endl;
        return;
    }
 
    // If no remaining elements,
    if (n == 0)
        return;
 
    // We consider two cases for every element.
    // a) We do not include last element.
    // b) We include last element in current subset.
    printAllSubsetsRec(arr, n - 1, v, sum);
    v.push_back(arr[n - 1]);
    printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1]);
}
 
// Wrapper over printAllSubsetsRec()
void printAllSubsets(int arr[], int n, int sum)
{
    vector<int> v;
    printAllSubsetsRec(arr, n, v, sum);
}
 
// Driver code
int main()
{
    int arr[] = { 2, 5, 8, 4, 6, 11 };
    int sum = 13;
    int n = sizeof(arr) / sizeof(arr[0]);
    printAllSubsets(arr, n, sum);
    return 0;
}
 
 

Java




// Java program to print all subsets with given sum
import java.util.*;
 class Solution
{
 
// The vector v stores current subset.
static void printAllSubsetsRec(int arr[], int n, Vector<Integer> v,
                        int sum)
{
    // If remaining sum is 0, then print all
    // elements of current subset.
    if (sum == 0) {
        for (int i=0;i<v.size();i++)
            System.out.print( v.get(i) + " ");
        System.out.println();
        return;
    }
 
    // If no remaining elements,
    if (n == 0)
        return;
 
    // We consider two cases for every element.
    // a) We do not include last element.
    // b) We include last element in current subset.
    printAllSubsetsRec(arr, n - 1, v, sum);
    Vector<Integer> v1=new Vector<Integer>(v);
    v1.add(arr[n - 1]);
    printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]);
}
 
// Wrapper over printAllSubsetsRec()
static void printAllSubsets(int arr[], int n, int sum)
{
    Vector<Integer> v= new Vector<Integer>();
    printAllSubsetsRec(arr, n, v, sum);
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 2, 5, 8, 4, 6, 11 };
    int sum = 13;
    int n = arr.length;
    printAllSubsets(arr, n, sum);
     
}
}
//contributed by Arnab Kundu
 
 

Python3




# Python program to print all subsets with given sum
 
# The vector v stores current subset.
def printAllSubsetsRec(arr, n, v, sum) :
 
    # If remaining sum is 0, then print all
    # elements of current subset.
    if (sum == 0) :
        for value in v :
            print(value, end=" ")
        print()
        return
     
 
    # If no remaining elements,
    if (n == 0):
        return
 
    # We consider two cases for every element.
    # a) We do not include last element.
    # b) We include last element in current subset.
    printAllSubsetsRec(arr, n - 1, v, sum)
    v1 = [] + v
    v1.append(arr[n - 1])
    printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1])
 
 
# Wrapper over printAllSubsetsRec()
def printAllSubsets(arr, n, sum):
 
    v = []
    printAllSubsetsRec(arr, n, v, sum)
 
 
# Driver code
 
arr = [ 2, 5, 8, 4, 6, 11 ]
sum = 13
n = len(arr)
printAllSubsets(arr, n, sum)
 
# This code is contributed by ihritik
 
 

C#




// C# program to print all subsets with given sum
using System;
using System.Collections.Generic;
 
class GFG
{
    // The vector v stores current subset.
    static void printAllSubsetsRec(int []arr, int n,
                                    List<int> v, int sum)
    {
        // If remaining sum is 0, then print all
        // elements of current subset.
        if (sum == 0)
        {
            for (int i = 0; i < v.Count; i++)
                Console.Write( v[i]+ " ");
            Console.WriteLine();
            return;
        }
 
        // If no remaining elements,
        if (n == 0)
            return;
 
        // We consider two cases for every element.
        // a) We do not include last element.
        // b) We include last element in current subset.
        printAllSubsetsRec(arr, n - 1, v, sum);
        List<int> v1 = new List<int>(v);
        v1.Add(arr[n - 1]);
        printAllSubsetsRec(arr, n - 1, v1, sum - arr[n - 1]);
    }
 
    // Wrapper over printAllSubsetsRec()
    static void printAllSubsets(int []arr, int n, int sum)
    {
        List<int> v = new List<int>();
        printAllSubsetsRec(arr, n, v, sum);
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = { 2, 5, 8, 4, 6, 11 };
        int sum = 13;
        int n = arr.Length;
        printAllSubsets(arr, n, sum);
    }
}
 
// This code is contributed by Rajput-Ji
 
 

PHP




<?php
// PHP program to print all subsets with given sum
 
// The vector v stores current subset.
function printAllSubsetsRec($arr, $n, $v, $sum)
{
    // If remaining sum is 0, then print all
    // elements of current subset.
    if ($sum == 0)
    {
        for ($i = 0; $i < count($v); $i++)
            echo $v[$i] . " ";
        echo "\n";
        return;
    }
 
    // If no remaining elements,
    if ($n == 0)
        return;
 
    // We consider two cases for every element.
    // a) We do not include last element.
    // b) We include last element in current subset.
    printAllSubsetsRec($arr, $n - 1, $v, $sum);
    array_push($v, $arr[$n - 1]);
    printAllSubsetsRec($arr, $n - 1, $v,
                       $sum - $arr[$n - 1]);
}
 
// Wrapper over printAllSubsetsRec()
function printAllSubsets($arr, $n, $sum)
{
    $v = array();
    printAllSubsetsRec($arr, $n, $v, $sum);
}
 
// Driver code
$arr = array( 2, 5, 8, 4, 6, 11 );
$sum = 13;
$n = count($arr);
printAllSubsets($arr, $n, $sum);
 
// This code is contributed by mits
?>
 
 

Javascript




<script>
  
        // JavaScript Program for the above approach
 
        // The vector v stores current subset.
        function printAllSubsetsRec(arr, n, v, sum) {
            // If remaining sum is 0, then print all
            // elements of current subset.
            if (sum == 0) {
                for (let x of v)
                    document.write(x + " ");
                document.write("<br>")
                return;
            }
 
            // If no remaining elements,
            if (n == 0)
                return;
 
            // We consider two cases for every element.
            // a) We do not include last element.
            // b) We include last element in current subset.
            printAllSubsetsRec(arr, n - 1, v, sum);
            v.push(arr[n - 1]);
            printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1]);
            v.pop();
        }
 
        // Wrapper over printAllSubsetsRec()
        function printAllSubsets(arr, n, sum) {
            let v = [];
            printAllSubsetsRec(arr, n, v, sum);
        }
 
        // Driver code
 
        let arr = [2, 5, 8, 4, 6, 11];
        let sum = 13;
        let n = arr.length;
        printAllSubsets(arr, n, sum);
 
    // This code is contributed by Potta Lokesh
 
</script>
 
 
Output: 
8 5  6 5 2  11 2

 

Time Complexity : O(2n)
Please refer below post for an optimized solution based on Dynamic Programming. 
Print all subsets with given sum using Dynamic Programming
 



Next Article
Print all subsets with given sum
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Print all subsets with given sum
    Given an array arr[] of non-negative integers and an integer target. The task is to print all subsets of the array whose sum is equal to the given target. Note: If no subset has a sum equal to target, print -1. Examples: Input: arr[] = [5, 2, 3, 10, 6, 8], target = 10Output: [ [5, 2, 3], [2, 8], [10
    15+ min read
  • Print all subarrays with sum in a given range
    Given an array arr[] of positive integers and two integers L and R defining the range [L, R]. The task is to print the subarrays having sum in the range L to R. Examples: Input: arr[] = {1, 4, 6}, L = 3, R = 8Output: {1, 4}, {4}, {6}.Explanation: All the possible subarrays are the following{1] with
    5 min read
  • Print sums of all subsets of a given set
    Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order. Examples : Input: arr[] = {2, 3}Output: 0 2 3 5Explanation: All subsets of this array are - {{}, {2}, {3}, {2, 3}}, having sums - 0, 2, 3 and 5 respectively.Input: arr[] = {2, 4, 5}Output: 0 2 4 5 6
    10 min read
  • Find all subarrays with sum in the given range
    Given an unsorted array of size, N. Find subarrays that add to a sum in the given range L-R. Examples: Input: arr[] = {2, 3, 5, 8}, L = 4, R = 13Output: The indexes of subarrays are {0, 1}, {0, 2}, {1, 2}, {2, 2}, {2, 3}, {3, 3} Input: arr[] = {1, 4, 6}, L = 3, R = 8Output: The indexes of subarrays
    4 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} s
    8 min read
  • Sum of all subsets of a given size (=K)
    Given an array arr[] consisting of N integers and a positive integer K, the task is to find the sum of all the subsets of size K. Examples: Input: arr[] = {1, 2, 4, 5}, K = 2Output: 36Explanation:The subsets of size K(= 2) are = {1, 2}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {4, 5}. Now, the sum of all sub
    7 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
    5 min read
  • Partition of a set into K subsets with equal sum
    Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset. Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
    9 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
    13 min read
  • Number of subsets with a given OR value
    Given an array arr[] of length N, the task is to find the number of subsets with a given OR value M.Examples: Input: arr[] = {2, 3, 2} M = 3 Output: 4 All possible subsets and there OR values are: {2} = 2 {3} = 3 {2} = 2 {2, 3} = 2 | 3 = 3 {3, 2} = 3 | 2 = 3 {2, 2} = 2 | 2 = 2 {2, 3, 2} = 2 | 3 | 2
    6 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