I want a function that returns all possible combinations of an alphabet X, the combinations have to be n long. I understand this had been done a million times before but I try to understand recursion.
Two things I don't understand:
One. The function inserts every last iteration of a series twice, so if alphabet is 'AB' and length is 2 I would expect:
AA
AB
BA
BB
but I get:
AA
AB
AB
BA
BB
BB
and 2. How can the function need the return within the outer loop. If I just remove the outer loop and leave return then I get segmentation fault.
In the function I keep the vector with me, I could also put it in global scope but the I have the same effect. I build the possible combination S on the fly and keep len en depth:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
void combirec(vector<string> &A, char S[20], char *alphabet, int len, int depth)
{
for (int i = 0; i < len; i++) {
for (int c = 0; c < strlen(alphabet); c++) {
S[depth] = alphabet[c];
combirec(A, S, alphabet, len-1, depth+1);
A.push_back(S);
}
return;
}
}
int main()
{
vector<string> A;
char S[20];
char alphabet[6] = "AB";
int len = 2;
S[len] = '\0';
combirec(A, S, alphabet, len, 0);
for (int i = 0 ; i < A.size(); i++)
cout << A[i] << endl;
}