#include #define N 5 #define M 2 void display(char* stack, int size) { printf("%s\n", stack); } void recurse(int n, int m, char* stack, int filled = 0) { // filled denotes how many elements of our stack are filled [ with valid data ] if (filled == 0) { // initiallize our base cases, 0 though (n - m) // - no point in setting anything higher than n-m because it will be pruned for (int x = 0; x <= n - m; ++x) { stack[0] = 'a' + x; // 'b' = 'a' + 1, 'c' = 'a' + 2, etc. recurse(n, m, stack, filled + 1); } return; } if (filled == m) { // if our stack is full, display it display(stack, m); return; } // stack[filled - 1] was the last char we put in. // extract that number (as element of n) by subtracting 'a' // starting at the next element, iterate up as far to n as will still allow us to fill // any unfilled elements of the stack (m - filled), thus, n - (m - filled) for (int x = (int)(stack[filled - 1] - 'a') + 1; x <= n - (m - filled); ++x) { stack[filled] = 'a' + x; recurse(n, m, stack, filled + 1); } return; } int main() { char* stack = new char[M + 1]; stack[M] = '\0'; recurse(N, M, stack); delete[] stack; }