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 submasks of a given mask
Next article icon

Print all subsets of given size of a set

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Generate all possible subsets of size r of the given array with distinct elements. 

Examples:  

Input  : arr[] = {1, 2, 3, 4}
r = 2
Output : 1 2
1 3
1 4
2 3
2 4
3 4
Input : arr[] = {10, 20, 30, 40, 50}
r = 3
Output : 10 20 30
10 20 40
10 20 50
10 30 40
10 30 50
10 40 50
20 30 40
20 30 50
20 40 50
30 40 50

This problem is the same Print all possible combinations of r elements in a given array of size n.
The idea here is similar to Subset Sum Problem. We, one by one, consider every element of the input array, and recur for two cases:

  1. The element is included in the current combination (We put the element in data[] and increase the next available index in data[]) 
  2. The element is excluded in the current combination (We do not put the element in and do not change the index)

When the number of elements in data[] becomes equal to r (size of a combination), we print it.

This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1

Implementation:

C++
// C++ Program to print all combination of size r in // an array of size n #include <iostream> using namespace std;  void combinationUtil(int arr[], int n, int r,                      int index, int data[], int i);   // The main function that prints all combinations of  // size r in arr[] of size n. This function mainly // uses combinationUtil() void printCombination(int arr[], int n, int r) {        // A temporary array to store all combination     // one by one     int data[r];       // Print all combination using temporary array 'data[]'     combinationUtil(arr, n, r, 0, data, 0); }   /* arr[]  ---> Input Array    n      ---> Size of input array    r      ---> Size of a combination to be printed    index  ---> Current index in data[]    data[] ---> Temporary array to store current combination    i      ---> index of current element in arr[]     */ void combinationUtil(int arr[], int n, int r, int index,                      int data[], int i) {     // Current combination is ready, print it     if (index == r) {         for (int j = 0; j < r; j++)             cout <<" "<< data[j];         cout <<"\n";         return;     }       // When no more elements are there to put in data[]     if (i >= n)         return;       // current is included, put next at next location     data[index] = arr[i];     combinationUtil(arr, n, r, index + 1, data, i + 1);       // current is excluded, replace it with next     // (Note that i+1 is passed, but index is not     // changed)     combinationUtil(arr, n, r, index, data, i + 1); }   // Driver program to test above functions int main() {     int arr[] = { 10, 20, 30, 40, 50 };     int r = 3;     int n = sizeof(arr) / sizeof(arr[0]);     printCombination(arr, n, r);     return 0; }  // This code is contributed by shivanisinghss2110  
C
// C++ Program to print all combination of size r in // an array of size n #include <stdio.h> void combinationUtil(int arr[], int n, int r,                      int index, int data[], int i);  // The main function that prints all combinations of  // size r in arr[] of size n. This function mainly // uses combinationUtil() void printCombination(int arr[], int n, int r) {     // A temporary array to store all combination     // one by one     int data[r];      // Print all combination using temporary array 'data[]'     combinationUtil(arr, n, r, 0, data, 0); }  /* arr[]  ---> Input Array    n      ---> Size of input array    r      ---> Size of a combination to be printed    index  ---> Current index in data[]    data[] ---> Temporary array to store current combination    i      ---> index of current element in arr[]     */ void combinationUtil(int arr[], int n, int r, int index,                      int data[], int i) {     // Current combination is ready, print it     if (index == r) {         for (int j = 0; j < r; j++)             printf("%d ", data[j]);         printf("\n");         return;     }      // When no more elements are there to put in data[]     if (i >= n)         return;      // current is included, put next at next location     data[index] = arr[i];     combinationUtil(arr, n, r, index + 1, data, i + 1);      // current is excluded, replace it with next     // (Note that i+1 is passed, but index is not     // changed)     combinationUtil(arr, n, r, index, data, i + 1); }  // Driver program to test above functions int main() {     int arr[] = { 10, 20, 30, 40, 50 };     int r = 3;     int n = sizeof(arr) / sizeof(arr[0]);     printCombination(arr, n, r);     return 0; } 
Java
// Java program to print all combination of size // r in an array of size n import java.io.*;  class Permutation {      /* arr[]  ---> Input Array     data[] ---> Temporary array to store current combination     start & end ---> Starting and Ending indexes in arr[]     index  ---> Current index in data[]     r ---> Size of a combination to be printed */     static void combinationUtil(int arr[], int n, int r,                           int index, int data[], int i)     {         // Current combination is ready to be printed,          // print it         if (index == r) {             for (int j = 0; j < r; j++)                 System.out.print(data[j] + " ");             System.out.println("");             return;         }          // When no more elements are there to put in data[]         if (i >= n)             return;          // current is included, put next at next         // location         data[index] = arr[i];         combinationUtil(arr, n, r, index + 1,                                 data, i + 1);          // current is excluded, replace it with         // next (Note that i+1 is passed, but         // index is not changed)         combinationUtil(arr, n, r, index, data, i + 1);     }      // The main function that prints all combinations     // of size r in arr[] of size n. This function      // mainly uses combinationUtil()     static void printCombination(int arr[], int n, int r)     {         // A temporary array to store all combination         // one by one         int data[] = new int[r];          // Print all combination using temporary         // array 'data[]'         combinationUtil(arr, n, r, 0, data, 0);     }      /* Driver function to check for above function */     public static void main(String[] args)     {         int arr[] = { 10, 20, 30, 40, 50 };         int r = 3;         int n = arr.length;         printCombination(arr, n, r);     } } /* This code is contributed by Devesh Agrawal */ 
Python
# Python3 program to print all # subset combination of n  # element in given set of r element .  # arr[] ---> Input Array # data[] ---> Temporary array to  #             store current combination # start & end ---> Starting and Ending  #                  indexes in arr[] # index ---> Current index in data[] # r ---> Size of a combination  #        to be printed  def combinationUtil(arr, n, r,                      index, data, i):     # Current combination is      # ready to be printed,     # print it     if(index == r):         for j in range(r):             print(data[j], end = " ")         print(" ")         return      # When no more elements      # are there to put in data[]     if(i >= n):         return      # current is included,      # put next at next     # location      data[index] = arr[i]     combinationUtil(arr, n, r,                      index + 1, data, i + 1)          # current is excluded,      # replace it with     # next (Note that i+1      # is passed, but index      # is not changed)     combinationUtil(arr, n, r, index,                      data, i + 1)   # The main function that # prints all combinations # of size r in arr[] of  # size n. This function  # mainly uses combinationUtil() def printcombination(arr, n, r):      # A temporary array to     # store all combination     # one by one     data = list(range(r))          # Print all combination      # using temporary      # array 'data[]'     combinationUtil(arr, n, r,                      0, data, 0)   # Driver Code arr = [10, 20, 30, 40, 50]  r = 3 n = len(arr) printcombination(arr, n, r)  # This code is contributed # by Ambuj sahu 
C#
// C# program to print all combination // of size r in an array of size n using System;  class GFG {      /* arr[] ---> Input Array     data[] ---> Temporary array to store     current combination start & end --->     Starting and Ending indexes in arr[]     index ---> Current index in data[]     r ---> Size of a combination to be     printed */     static void combinationUtil(int []arr,                   int n, int r, int index,                           int []data, int i)     {                  // Current combination is ready to         // be printed, print it         if (index == r)         {             for (int j = 0; j < r; j++)                 Console.Write(data[j] + " ");                              Console.WriteLine("");                          return;         }          // When no more elements are there         // to put in data[]         if (i >= n)             return;          // current is included, put next         // at next location         data[index] = arr[i];         combinationUtil(arr, n, r, index + 1,                                  data, i + 1);          // current is excluded, replace         // it with next (Note that i+1          // is passed, but index is not         // changed)         combinationUtil(arr, n, r, index,                                 data, i + 1);     }      // The main function that prints all     // combinations of size r in arr[] of     // size n. This function mainly uses     // combinationUtil()     static void printCombination(int []arr,                                 int n, int r)     {                  // A temporary array to store all         // combination one by one         int []data = new int[r];          // Print all combination using         // temporary array 'data[]'         combinationUtil(arr, n, r, 0, data, 0);     }      /* Driver function to check for     above function */     public static void Main()     {         int []arr = { 10, 20, 30, 40, 50 };         int r = 3;         int n = arr.Length;                  printCombination(arr, n, r);     } }  // This code is contributed by vt_m. 
JavaScript
<script>     // Javascript program to print all combination     // of size r in an array of size n          /* arr[] ---> Input Array     data[] ---> Temporary array to store     current combination start & end --->     Starting and Ending indexes in arr[]     index ---> Current index in data[]     r ---> Size of a combination to be     printed */     function combinationUtil(arr, n, r, index, data, i)     {                   // Current combination is ready to         // be printed, print it         if (index == r)         {             for (let j = 0; j < r; j++)                 document.write(data[j] + " ");                               document.write("</br>");                           return;         }           // When no more elements are there         // to put in data[]         if (i >= n)             return;           // current is included, put next         // at next location         data[index] = arr[i];         combinationUtil(arr, n, r, index + 1,                                 data, i + 1);           // current is excluded, replace         // it with next (Note that i+1         // is passed, but index is not         // changed)         combinationUtil(arr, n, r, index,                                 data, i + 1);     }       // The main function that prints all     // combinations of size r in arr[] of     // size n. This function mainly uses     // combinationUtil()     function printCombination(arr, n, r)     {                   // A temporary array to store all         // combination one by one         let data = new Array(r);         data.fill(0);           // Print all combination using         // temporary array 'data[]'         combinationUtil(arr, n, r, 0, data, 0);     }          let arr = [ 10, 20, 30, 40, 50 ];     let r = 3;     let n = arr.length;      printCombination(arr, n, r);      </script> 
PHP
<?php // Program to print all combination of  // size r in an array of size n  // The main function that prints all  // combinations of size r in arr[] of // size n. This function mainly uses // combinationUtil() function printCombination( $arr, $n, $r) {     // A temporary array to store all      // combination one by one     $data = array();      // Print all combination using      // temporary array 'data[]'     combinationUtil($arr, $n, $r, 0, $data, 0); }  /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store  current combination i ---> index of current element in arr[] */ function combinationUtil( $arr, $n, $r, $index,                     $data, $i) {     // Current combination is ready, print it     if ($index == $r) {         for ( $j = 0; $j < $r; $j++)             echo $data[$j]," ";         echo "\n";         return;     }      // When no more elements are there to     // put in data[]     if ($i >= $n)         return;      // current is included, put next at      // next location     $data[$index] = $arr[$i];     combinationUtil($arr, $n, $r, $index + 1,                                $data, $i + 1);      // current is excluded, replace it with     // next (Note that i+1 is passed, but      // index is not changed)     combinationUtil($arr, $n, $r, $index,                              $data, $i + 1); }  // Driver program to test above functions     $arr = array( 10, 20, 30, 40, 50 );     $r = 3;     $n = count($arr);     printCombination($arr, $n, $r);  // This code is contributed by anuj_67. ?> 

Output
 10 20 30  10 20 40  10 20 50  10 30 40  10 30 50  10 40 50  20 30 40  20 30 50  20 40 50  30 40 50

Time complexity of this algorithm is O(n*r). The outer loop runs n times and the inner loop runs r times.
Auxiliary Space: O(r), the space complexity is O(r) because we are creating a temporary array of size r and storing the combinations 
in it.

Approach 2: Using DP

The given program generates combinations of size r from an array of size n using a recursive approach. It does not use dynamic programming (DP) explicitly. However, dynamic programming can be applied to optimize the solution by avoiding redundant computations.

To implement a DP approach, we can use a 2D table to store the intermediate results and avoid recomputing the same combinations. Here’s an updated version of the program that incorporates dynamic programming:

C++
#include <iostream> #include <vector> using namespace std;  // Function to print all combinations of size r // using a dynamic programming approach void printCombination(int arr[], int n, int r) {     vector<vector<int>> dp(n + 1, vector<int>(r + 1, 0));      // Calculate the combinations using dynamic programming     for (int i = 0; i <= n; i++) {         for (int j = 0; j <= min(i, r); j++) {             if (j == 0 || j == i)                 dp[i][j] = 1;             else                 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];         }     }      // Print the combinations     for (int i = 0; i < dp[n].size(); i++) {         if (dp[n][i] == 0)             break;         for (int j = 0; j < dp[n][i]; j++) {             cout << arr[i] << " ";         }         cout << endl;     } }  // Driver program to test above functions int main() {     int arr[] = { 10, 20, 30, 40, 50 };     int r = 3;     int n = sizeof(arr) / sizeof(arr[0]);     printCombination(arr, n, r);     return 0; } 
Java
import java.util.ArrayList; import java.util.List;  public class GFG {     // Function to print all combinations of size r     // using a dynamic programming approach     public static void printCombination(int[] arr, int n, int r) {         List<List<Integer>> dp = new ArrayList<>(n + 1);         for (int i = 0; i <= n; i++) {             dp.add(new ArrayList<>(r + 1));             for (int j = 0; j <= r; j++) {                 dp.get(i).add(0);             }         }          // Calculate the combinations using dynamic programming         for (int i = 0; i <= n; i++) {             for (int j = 0; j <= Math.min(i, r); j++) {                 if (j == 0 || j == i) {                     dp.get(i).set(j, 1);                 } else {                     int val1 = dp.get(i - 1).get(j - 1);                     int val2 = dp.get(i - 1).get(j);                     dp.get(i).set(j, val1 + val2);                 }             }         }          // Print the combinations         for (int i = 0; i < dp.get(n).size(); i++) {             int count = dp.get(n).get(i);             if (count == 0) {                 break;             }             for (int j = 0; j < count; j++) {                 System.out.print(arr[i] + " ");             }             System.out.println();         }     }      // Driver program to test above functions     public static void main(String[] args) {         int[] arr = { 10, 20, 30, 40, 50 };         int r = 3;         int n = arr.length;         printCombination(arr, n, r);     } } 
Python
def print_combination(arr, n, r):     # Create a 2D list to store combinations     dp = [[0] * (r + 1) for _ in range(n + 1)]      # Calculate the combinations using dynamic programming     for i in range(n + 1):         for j in range(min(i, r) + 1):             if j == 0 or j == i:                 dp[i][j] = 1             else:                 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]      # Print the combinations     for i in range(len(dp[n])):         if dp[n][i] == 0:             break         for j in range(dp[n][i]):             print(arr[i], end=" ")  # Print the element 'arr[i]' 'dp[n][i]' times         print()  # Move to the next line for the next element  # Driver program to test the function if __name__ == "__main__":     arr = [10, 20, 30, 40, 50]     r = 3  # Size of combinations     n = len(arr)     print_combination(arr, n, r)      # This code is contributed by shivamgupta0987654321 
C#
using System; using System.Collections.Generic;  public class GFG {     // Function to print all combinations of size r     // using a dynamic programming approach     public static void PrintCombination(int[] arr, int n,                                         int r)     {         List<List<int> > dp = new List<List<int> >(n + 1);          for (int i = 0; i <= n; i++) {             dp.Add(new List<int>(r + 1));              for (int j = 0; j <= r; j++) {                 dp[i].Add(0);             }         }          // Calculate the combinations using dynamic         // programming         for (int i = 0; i <= n; i++) {             for (int j = 0; j <= Math.Min(i, r); j++) {                 if (j == 0 || j == i) {                     dp[i][j] = 1;                 }                 else {                     int val1 = dp[i - 1][j - 1];                     int val2 = dp[i - 1][j];                     dp[i][j] = val1 + val2;                 }             }         }          // Print the combinations         for (int i = 0; i < dp[n].Count; i++) {             int count = dp[n][i];             if (count == 0) {                 break;             }             for (int j = 0; j < count; j++) {                 Console.Write(arr[i] + " ");             }             Console.WriteLine();         }     }      // Driver program to test above functions     public static void Main(string[] args)     {         int[] arr = { 10, 20, 30, 40, 50 };         int r = 3;         int n = arr.Length;         PrintCombination(arr, n, r);     } } 
JavaScript
function printCombination(arr, n, r) {     let dp = new Array(n + 1);     for (let i = 0; i <= n; i++) {         dp[i] = new Array(r + 1).fill(0);     }      // Calculate the combinations using dynamic programming     for (let i = 0; i <= n; i++) {         for (let j = 0; j <= Math.min(i, r); j++) {             if (j === 0 || j === i) {                 dp[i][j] = 1;             } else {                 let val1 = dp[i - 1][j - 1];                 let val2 = dp[i - 1][j];                 dp[i][j] = val1 + val2;             }         }     }      // Print the combinations     for (let i = 0; i < dp[n].length; i++) {         let count = dp[n][i];         if (count === 0) {             break;         }         for (let j = 0; j < count; j++) {             console.log(arr[i] + " ");         }         console.log();     } }  // Driver program to test above function let arr = [10, 20, 30, 40, 50]; let r = 3; let n = arr.length; printCombination(arr, n, r); 

Output
10  20 20 20 20 20  30 30 30 30 30 30 30 30 30 30  40 40 40 40 40 40 40 40 40 40 

Time complexity of this algorithm is O(n*r).The outer loop runs n times and the inner loop runs r times.

Auxiliary Space: O(n*r).

Another Approach(using BitMasking):

Follow the below steps to solve the above problem:

1) Generate all possible binary numbers with a length equal to the number of elements in the set. Each binary number will represent a potential subset.
2) Iterate through each binary number from 0 to 2^N – 1, where N is the number of elements in the set. This represents all possible subsets of the set.
3) For each binary number, check the number of set bits(1s). If the count of set bits is equal to the desired subset size, consider it as a valid subset.
4) To extract the elements of the subset, iterate through the bits of the binary number. If a bit is set (1), include the corresponding element from the set in the subset.
5) Print the desired output.

Below is the implementation of above approach:

C++
#include <bits/stdc++.h> using namespace std;  void printSubset(int arr[], int subset[], int r) {     for (int i = 0; i < r; i++)         cout << subset[i] << " ";     cout << endl; }  void printCombination(int arr[], int n, int r) {     int totalSubsets = 1 << n;  // Total number of subsets is 2^n     for (int bitmask = 0; bitmask < totalSubsets; bitmask++) {         // Count the number of set bits in the bitmask         int count = 0;         int temp = bitmask;         while (temp > 0) {             count += temp & 1;             temp >>= 1;         }          if (count == r) {             int subset[r];             int index = 0;             for (int i = 0; i < n; i++) {                 if (bitmask & (1 << i))                     subset[index++] = arr[i];             }             printSubset(arr, subset, r);         }     } }  int main() {     int arr[] = {10, 20, 30, 40, 50};     int r = 3;     int n = sizeof(arr) / sizeof(arr[0]);      printCombination(arr, n, r);      return 0; } // This code is contributed by Yash Agarwal(yashagarwal2852002) 
Java
public class Main {     // Function to print a subset of the array     public static void printSubset(int[] arr, int[] subset, int r) {         for (int i = 0; i < r; i++)             System.out.print(subset[i] + " ");         System.out.println();     }      // Function to print combinations of 'r' elements from array 'arr'     public static void printCombination(int[] arr, int n, int r) {         int totalSubsets = 1 << n;  // Total number of subsets is 2^n         for (int bitmask = 0; bitmask < totalSubsets; bitmask++) {             // Count the number of set bits (1s) in the bitmask             int count = 0;             int temp = bitmask;             while (temp > 0) {                 count += temp & 1;  // Check the least significant bit                 temp >>= 1;        // Right shift the bitmask             }              if (count == r) {                 int[] subset = new int[r];                 int index = 0;                 for (int i = 0; i < n; i++) {                     if ((bitmask & (1 << i)) != 0)  // Check if the i-th bit is set                         subset[index++] = arr[i];                 }                 printSubset(arr, subset, r);  // Print the current combination             }         }     }      public static void main(String[] args) {         int[] arr = {10, 20, 30, 40, 50};         int r = 3;  // Size of the subsets         int n = arr.length;  // Number of elements in the array          printCombination(arr, n, r);  // Find and print combinations     } } 
Python
def print_subset(arr, subset, r):     # Function to print a subset     for i in range(r):         print(subset[i]),         if i < r - 1:             print(" "),     print()   def print_combination(arr, n, r):     # Function to print combinations of elements from arr     total_subsets = 1 << n  # Total number of subsets is 2^n      # Iterate through all possible subsets     for bitmask in range(total_subsets):         # Count the number of set bits in the bitmask         count = bin(bitmask).count('1')          # Check if the count of set bits is equal to r         if count == r:             subset = [0] * r             index = 0              # Build the subset using elements corresponding to set bits             for i in range(n):                 if bitmask & (1 << i):                     subset[index] = arr[i]                     index += 1              # Print the subset             print_subset(arr, subset, r)   if __name__ == "__main__":     arr = [10, 20, 30, 40, 50]     r = 3     n = len(arr)      # Call the print_combination function to print combinations     print_combination(arr, n, r) 
C#
using System;  class GFG {     static void PrintSubset(int[] arr, int[] subset, int r)     {         for (int i = 0; i < r; i++)             Console.Write(subset[i] + " ");         Console.WriteLine();     }      static void PrintCombination(int[] arr, int n, int r)     {         int totalSubsets = 1 << n; // Total number of subsets is 2^n         for (int bitmask = 0; bitmask < totalSubsets; bitmask++)         {             // Count the number of set bits in the bitmask             int count = 0;             int temp = bitmask;             while (temp > 0)             {                 count += temp & 1;                 temp >>= 1;             }              if (count == r)             {                 int[] subset = new int[r];                 int index = 0;                 for (int i = 0; i < n; i++)                 {                     if ((bitmask & (1 << i)) > 0)                         subset[index++] = arr[i];                 }                 PrintSubset(arr, subset, r);             }         }     }      static void Main()     {         int[] arr = { 10, 20, 30, 40, 50 };         int r = 3;         int n = arr.Length;          PrintCombination(arr, n, r);      } } 
JavaScript
function printSubset(arr, subset, r) {     for (let i = 0; i < r; i++)         process.stdout.write(subset[i] + " ");     process.stdout.write("\n"); }  function printCombination(arr, n, r) {     let totalSubsets = 1 << n; // Total number of subsets is 2^n     for (let bitmask = 0; bitmask < totalSubsets; bitmask++) {         // Count the number of set bits in the bitmask         let count = 0;         let temp = bitmask;         while (temp > 0) {             count += temp & 1;             temp >>= 1;         }          if (count === r) {             let subset = new Array(r);             let index = 0;             for (let i = 0; i < n; i++) {                 if (bitmask & (1 << i))                     subset[index++] = arr[i];             }             printSubset(arr, subset, r);         }     } }  let arr = [10, 20, 30, 40, 50]; let r = 3; let n = arr.length;  printCombination(arr, n, r); 

Output
10 20 30  10 20 40  10 30 40  20 30 40  10 20 50  10 30 50  20 30 50  10 40 50  20 40 50  30 40 50 

Time Complexity: O(2^n), where n is the number of elements in the given array.

Auxiliary Space: O(n+r)

Refer to the post below for more solutions and ideas to handle duplicates in the input array. 
Print all possible combinations of r elements in a given array of size n.

 



Next Article
Print all submasks of a given mask
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • Combinatorial
  • DSA
Practice Tags :
  • Arrays
  • Combinatorial

Similar Reads

  • 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
  • Print all subsets of a given Set or Array
    Given an array arr of size n, your task is to print all the subsets of the array in lexicographical order. A subset is any selection of elements from an array, where the order does not matter, and no element appears more than once. It can include any number of elements, from none (the empty subset)
    12 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
  • Print all submasks of a given mask
    Given an integer N, the task is to print all the subsets of the set formed by the set bits present in the binary representation of N. Examples: Input: N = 5Output: 5 4 1 Explanation:Binary representation of N is "101", Therefore all the required subsets are {"101", "100", "001", "000"}. Input: N = 2
    4 min read
  • Given a set, find XOR of the XOR's of all subsets.
    The question is to find XOR of the XOR's of all subsets. i.e if the set is {1,2,3}. All subsets are : [{1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]. Find the XOR of each of the subset and then find the XOR of every subset result.We strongly recommend you to minimize your browser and try this yo
    5 min read
  • Find all Unique Subsets of a given Set
    Given an array A[] of positive integers, print all the unique non-empty subsets of the array  Note: The set can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples:  Input: A[] = {1, 5, 6}Output: {{1}, {1, 5}, {1, 6}, {5}, {5, 6}, {6}, {1, 5,
    15+ min read
  • 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
  • Finding all subsets of a given set in Java
    Problem: Find all the subsets of a given set. Input: S = {a, b, c, d} Output: {}, {a} , {b}, {c}, {d}, {a,b}, {a,c}, {a,d}, {b,c}, {b,d}, {c,d}, {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d} The total number of subsets of any given set is equal to 2^ (no. of elements in the set). If we carefully not
    2 min read
  • Sum of bitwise OR of all possible subsets of given set
    Given an array arr[] of size n, we need to find sum of all the values that comes from ORing all the elements of the subsets. Prerequisites : Subset Sum of given set Examples : Input : arr[] = {1, 2, 3} Output : 18 Total Subsets = 23 -1= 7 1 = 1 2 = 2 3 = 3 1 | 2 = 3 1 | 3 = 3 2 | 3 = 3 1 | 2 | 3 = 3
    8 min read
  • Product of Primes of all Subsets
    Given an array a[] of size N. The value of a subset is the product of primes in that subset. A non-prime is considered to be 1 while finding value by-product. The task is to find the product of the value of all possible subsets. Examples: Input: a[] = {3, 7} Output: 20 The subsets are: {3} {7} {3, 7
    8 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