forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAll_Codes_Recursion.cpp
More file actions
89 lines (70 loc) · 1.87 KB
/
All_Codes_Recursion.cpp
File metadata and controls
89 lines (70 loc) · 1.87 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Problem Statement
Assume that the value of a = 1, b = 2, c = 3, ... , z = 26.
You are given a numeric string S.
Write a program to return the list of all possible codes that can be generated from the given string.
For Example -
Input:
1123
Output:
aabc
kbc
alc
aaw
kw
Being a recursive solution, this won't work for large inputs. But we can use DP to make it work for Large results.
*/
#include <iostream>
#include<string.h>
using namespace std;
int getString(string str) {
int res = 99999;
if(str.size() == 1) {
int num = str[0] - '0';
//c = 'a' + (num-1);
return num-1;
}
else if(str.size() > 1) {
int num = ((str[0] - '0')*10) + (str[1] - '0');
if(num > 26) {
return res;
}
else {
//c = 'a' + (num-1);
return num-1;
}
}
return res;
}
int helper(string input, string curString, string modString, string output[10000]) {
static int i;
int cs = getString(curString);
if(input.empty() && cs < 27) {
modString +=('a' + cs);
output[i++] = modString;
return i;
}
if(cs < 27) {
modString +=('a' + cs);
}
int count = helper(input.substr(1),input.substr(0,1),modString,output);
if(input.length() > 1) {
int check = getString(input.substr(0,2));
if(check < 27) {
count = helper(input.substr(2),input.substr(0,2),modString,output);
}
}
return count;
}
int getCodes(string input, string output[10000]) {
return helper(input,"","",output);
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input, output);
for(int i = 0; i < count && i < 10000; i++)
cout << output[i] << endl;
return 0;
}