« Return subsequences of a string
Problem
Given a string, we have to find out all subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.
Input Format:
A string
Output Format:
Print all the subsequences of a string in different lines
Sample Input :
abc
Sample Output :
""
a
b
c
ab
bc
ac
abc
Solution
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int subs(string input, string output[])15{16 if (input.empty())17 {18 output[0] = "";19 return 1;20 }2122 string smallString = input.substr(1);23 int smallOutputSize = subs(smallString, output);24 for (int i = 0; i < smallOutputSize; i++)25 {26 output[i + smallOutputSize] = input[0] + output[i];27 }28 return 2 * smallOutputSize;29}3031int main()32{33 /*34 abc ["", a, b, c, ab, bc, ac, abc]3536 pow(2, n) is total number of subsequences.3738 As for every character we have to make39 a choice whether to include or not40 include the character.4142 difference between subsequences and substrings:43 substrings are continuous.44 For subsequences we can pick any characters45 */4647 string input;48 cin >> input;49 int x = pow(2, input.size());5051 string *output = new string[x];52 int count = subs(input, output);5354 for (int i = 0; i < count; i++)55 {56 cout << output[i] << endl;57 }58 return 0;59}