Recursion - All subsequences(output is not coming );

#include<bits/stdc++.h>

using namespace std;

void all_subseq(string str,string ans)
{

if(str.length()==0){
 cout<<ans<endl;
    return;}

for(int i=0;i<str.length();i++)
{
	char ch=str[i];
	string ros=str.substr(i+1);
	all_subseq(ros,ans+ch);

}

}

int main()
{
int n;
cin>>n;
while(n>0)
{
string str;
cin>>str;
sort(str.begin(),str.end());
all_subseq(str,"");
n–;
}

return 0;

}

hi sachin
there is no loop required in the recursive function and there is no need to sort the string also.
char ch=str[0];
string ros=str.substr(1);
print(ros,ans+ch); // include the current char
print(ros,ans); // do not include move forward

1 Like

the output is not in lexicographical order.

we need to print subsequences in lexicographical order

can you please provide the exact question.

Recursion - All subsequences
Print all the subsequences of a string in lexicographical order.

Input Format:
First line contains an integer N, the no of strings.
Next, N lines follows one string per line.
Constraints:
1 < len(str) < 20
Output Format:
No of subsequences one per line

Sample Input:
1
ab
Sample Output:

a
ab
b
Explanation:
4 subsequences are printed.
Empty string is a subsequence.

yes for the lexographical order you need to sort the array at the end

#include
#include
using namespace std;

void all_subseq(string str,string ans)
{

if(str.length()==0){
     cout<<ans<<endl;
	return;}

	char ch=str[0];
	string ros=str.substr(1);
	all_subseq(ros,ans+ch);
	all_subseq(ros,ans);

}

int main()
{
int n;
cin>>n;
while(n>0)
{
string str;
cin>>str;
sort(str.begin(),str.end());
all_subseq(str,"");
n–;
}

return 0;

}

the output of this code is
1
ab
ab
a
b

input

1
ab
output
ab
a
b

the output is coming is wrong

for the lexographical order you need to write your own compare function in the sort function that would sort it lexographically

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like