Skip to content

Instantly share code, notes, and snippets.

@zaccone
Created August 24, 2016 23:15
Show Gist options
  • Save zaccone/7506660a7ea87ef3b64df4443d074575 to your computer and use it in GitHub Desktop.
Save zaccone/7506660a7ea87ef3b64df4443d074575 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
static const size_t LETTERS = 26;
void permutations(char *str, size_t idx, size_t size, char *letters)
{
if (idx == size) {
printf("%s\n", str);
return;
}
for (size_t i = 0; i < LETTERS; i++) {
if (!letters[i])
continue;
str[idx] = i + 'a';
letters[i]--;
permutations(str, idx + 1, size, letters);
letters[i]++;
}
}
void permutation(const char *str)
{
size_t size = strlen(str);
char result[size + 1];
result[size] = '\0';
static char letters[LETTERS];
//memset(letters, 0, sizeof(letters));
for (size_t i = 0; i < size; i++) {
letters[str[i] - 'a']++;
}
permutations(result, 0, size, letters);
}
int main()
{
const char *str = "abc";
permutation(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment