-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPrint all Subsequences of a string
75 lines (60 loc) · 1.53 KB
/
Print all Subsequences of a string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
C++ code
#include <iostream>
using namespace std;
int subs(string input, string output[]) {
if (input.empty()) {
output[0] = "";
return 1;
}
string smallString = input.substr(1);
int smallOutputSize = subs(smallString, output);
for (int i = 0; i < smallOutputSize; i++) {
output[i + smallOutputSize] = input[0] + output[i];
}
return 2 * smallOutputSize;
}
int main() {
string input;
cin >> input;
string* output = new string[1000];
int count = subs(input, output);
for (int i = 0; i < count; i++) {
cout << output[i] << endl;
}
}
// or just printing the strings and not returning them
#include <iostream>
using namespace std;
void print_subs(string input, string output) {
if (input.length() == 0) {
cout << output << endl;
return;
}
print_subs(input.substr(1), output);
print_subs(input.substr(1), output + input[0]);
}
int main() {
string input;
cin >> input;
string output = "";
print_subs(input, output);
}
-----------------------------
Python 3.5
def subs(inp,output):# inp is the input string and output is the final output array
# base case
if(len(inp)==0):
output[0]=""
return 1
smallString=inp[1:]
smallOutput=subs(smallString,output)
for i in range(smallOutput):
output[i+smallOutput]=inp[0]+output[i]
return 2*smallOutput
string=input().strip()
import math
sizeofoutput=math.pow(2,len(string))
output=[None]*int(sizeofoutput)
count=subs(string,output)
for i in range(count):
print(output[i]) # the first one is the empty , so you cant see it