C++
x
32
1
2
3
4
using namespace std;
5
6
class Solution {
7
public:
8
9
void print_str(const string& s){
10
cout<<s<<endl;
11
}
12
void recur(const string& st, string ans, int i, int n){
13
if (i >= n){
14
if (ans!="") print_str(ans); // print non-empty answer
15
}else if(ans==""){ // when current answer is empty
16
recur(st, ans+st[i], i+1, n); // start appending characters to the answer
17
recur(st, ans, i+1, n); // or keep the answer empty
18
}else{
19
print_str(ans); // print non-empty answer
20
recur(st, ans+st[i], i+1, n); // append a character (no choice to skip a character)
21
}
22
}
23
24
};
25
26
27
int main()
28
{
29
Solution sol;
30
string st = "ABCD";
31
sol.recur(st, "", 0, st.length());
32
}
$ g++ prog.cc -Wall -Wextra -std=c++11 -pedantic
Start
A AB ABC ABCD B BC BCD C CD D
0
Finish