I am having a string let say ABCD
I want to create all the subsets in such a way that they are consecutive like this:
`A` ,`AB`, `ABC`, `ABCD`, `B`, `BC`, `BCD`, `C`, `CD`, `D`
AC, AD, BD
etc should not be generated as they are not next to each other.
I tried to write the logic but now I am getting:
See the highlighted ones. Is it possible to generate consecutive subset using recursion?
Reason for using recursion is to understand how the recursion works so I am attempting all the questions using recursion only (without loops)
Code:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void print_str(string s){
for(int i=0; i<s.length();i++)
{
cout<<s[i];
}
cout<<endl;
}
void recur(string st, string ans, int prev, int n, int ind){
print_str(ans);
for(int i=prev; i<n;i++){
recur(st, ans+st[i], i+1, n, ind+1);
}
}
};
int main()
{
Solution sol;
string st = "ABCD";
sol.recur(st, "", 0, st.length(),0);
}
With recursion, you might do:
void print_seq(std::string_view s)
{
if (s.size() > 1) print_seq(s.substr(0, s.size() - 1));
std::cout << s << std::endl;
}
void print_all(std::string_view s)
{
print_seq(s);
if (s.size() > 1) print_all(s.substr(1));
}
int main()
{
print_all("ABCD");
}
From your rules, it can be said that once you started to append something to ans
, you mustn't skip characters.
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
void print_str(const string& s){
cout<<s<<endl;
}
void recur(const string& st, string ans, int i, int n){
if (i >= n){
if (ans!="") print_str(ans); // print non-empty answer
}else if(ans==""){ // when current answer is empty
recur(st, ans+st[i], i+1, n); // start appending characters to the answer
recur(st, ans, i+1, n); // or keep the answer empty
}else{
print_str(ans); // print non-empty answer
recur(st, ans+st[i], i+1, n); // append a character (no choice to skip a character)
}
}
};
int main()
{
Solution sol;
string st = "ABCD";
sol.recur(st, "", 0, st.length());
}
Output :
A
AB
ABC
ABCD
B
BC
BCD
C
CD
D
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.