Generate all distinct subsequences of array using backtracking

Given an array arr[] consisting of N positive integers, the task is to generate all distinct subsequences of the array.

Examples:

Input: arr[] = {1, 2, 2}
Output: {} {1} {1, 2} {1, 2, 2} {2} {2, 2}
Explanation:
The total subsequences of the given array are {}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1, 2, 2}.
Since {2} and {1, 2} are repeated twice, print all the remaining subsequences of the array.

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

 

Approach: Follow the steps below to solve the problem:



  1. Sort the given array.
  2. Initialize a vector of vectors to store all distinct subsequences.
  3. Traverse the array and considering two choices for each array element, to include it in a subsequence or not to include it.
  4. If duplicates are found, ignore them and check for the remaining elements. Otherwise, add the current array element to the current subsequence and traverse the remaining elements to generate subsequences.
  5. After generating the subsequences, remove the current array element.

Below is the implementation of the above approach:

C++14

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to generate all distinct
// subsequences of the array using backtracking
void backtrack(vector<int>& nums, int start,
               vector<vector<int> >& resultset,
               vector<int> curr_set)
{
    resultset.push_back(curr_set);
 
    for (int i = start; i < nums.size(); i++) {
 
        // If the current element is repeating
        if (i > start
            && nums[i] == nums[i - 1]) {
            continue;
        }
 
        // Include current element
        // into the subsequence
        curr_set.push_back(nums[i]);
 
        // Proceed to the remaining array
        // to generate subsequences
        // including current array element
        backtrack(nums, i + 1, resultset,
                  curr_set);
 
        // Remove current element
        // from the subsequence
        curr_set.pop_back();
    }
}
 
// Function to sort the array and generate
// subsequences using Backtracking
vector<vector<int> > AllSubsets(
    vector<int> nums)
{
    // Stores the subsequences
    vector<vector<int> > resultset;
 
    // Stores the current
    // subsequence
    vector<int> curr_set;
 
    // Sort the vector
    sort(nums.begin(), nums.end());
 
    // Backtrack function to
    // generate subsequences
    backtrack(nums, 0, resultset,
              curr_set);
 
    // Return the result
    return resultset;
}
 
// Function to print all subsequences
void print(vector<vector<int> > result)
{
    for (int i = 0; i < result.size();
         i++) {
 
        cout << "{";
        for (int j = 0; j < result[i].size();
             j++) {
 
            cout << result[i][j];
            if (j < result[i].size() - 1) {
 
                cout << ", ";
            }
        }
        cout << "} ";
    }
}
 
// Driver Code
int main()
{
    vector<int> v{ 1, 2, 2 };
 
    // Function call
    vector<vector<int> > result
        = AllSubsets(v);
 
    // Print function
    print(result);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to generate all distinct
// subsequences of the array using backtracking
public static void backtrack(ArrayList<Integer> nums,
                             int start,
                             ArrayList<Integer> curr_set)
{
    System.out.print(curr_set + " ");
 
    for(int i = start; i < nums.size(); i++)
    {
         
        // If the current element is repeating
        if (i > start &&
            nums.get(i) == nums.get(i - 1))
        {
            continue;
        }
 
        // Include current element
        // into the subsequence
        curr_set.add(nums.get(i));
 
        // Proceed to the remaining array
        // to generate subsequences
        // including current array element
        backtrack(nums, i + 1, curr_set);
 
        // Remove current element
        // from the subsequence
        curr_set.remove(curr_set.size() - 1);
    }
}
 
// Function to sort the array and generate
// subsequences using Backtracking
public static void AllSubsets(ArrayList<Integer> nums)
{
 
    // Stores the current
    // subsequence
    ArrayList<Integer> curr_set = new ArrayList<>();
 
    // Sort the vector
    Collections.sort(nums);
 
    // Backtrack function to
    // generate subsequences
    backtrack(nums, 0, curr_set);
}
 
// Driver Code
public static void main(String[] args)
{
    ArrayList<Integer> v = new ArrayList<>();
    v.add(1);
    v.add(2);
    v.add(2);
     
    // Function call
    AllSubsets(v);
}
}
 
// This code is contributed by hemanthswarna1506

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Function to generate all distinct
// subsequences of the array using
// backtracking
public static void backtrack(List<int> nums,
                             int start,
                             List<int> curr_set)
{
  Console.Write(" {");
   
  foreach(int i in curr_set)
  {
    Console.Write(i);
    Console.Write(", ");
  }
 
  Console.Write("}");
   
  for(int i = start;
          i < nums.Count; i++)
  {
    // If the current element
    // is repeating
    if (i > start &&
        nums[i] == nums[i - 1])
    {
      continue;
    }
 
    // Include current element
    // into the subsequence
    curr_set.Add(nums[i]);
 
    // Proceed to the remaining array
    // to generate subsequences
    // including current array element
    backtrack(nums, i + 1, curr_set);
 
    // Remove current element
    // from the subsequence
    curr_set.Remove(curr_set.Count - 1);
  }
}
 
// Function to sort the array and generate
// subsequences using Backtracking
public static void AllSubsets(List<int> nums)
{
  // Stores the current
  // subsequence
  List<int> curr_set = new List<int>();
 
  // Sort the vector
  nums.Sort();
 
  // Backtrack function to
  // generate subsequences
  backtrack(nums, 0, curr_set);
}
 
// Driver Code
public static void Main(String[] args)
{
  List<int> v = new List<int>();
  v.Add(1);
  v.Add(2);
  v.Add(2);
 
  // Function call
  AllSubsets(v);
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output

{} {1} {1, 2} {1, 2, 2} {2} {2, 2} 

Time Complexity: O(2N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.