/* Just enter a string, say "abcd" and it will print all possible combinations, i.e., abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba */ # include <stdio.h> # include <string.h> void combination(char *first, char *second) { int lensecond = strlen(second); if (!lensecond) { printf("%s\t", first); return; } char * tmpfirst = new char[strlen(first) + 2]; char * tmpsecond = new char[lensecond]; int i, j, k; for (i = 0; i < lensecond; i++) { sprintf(tmpfirst, "%s%c\0", first, second[i]); for (j = 0, k = 0; j < lensecond; j++) { if (j != i) { tmpsecond[k++] = second[j]; } } tmpsecond[k] = '\0'; combination(tmpfirst, tmpsecond); } delete tmpfirst; delete tmpsecond; } void main() { char string[100]; printf("Enter the string: "); scanf("%s", string); combination("", string); }
Copyright © 1999-2008 Krishna Kumar, All Rights Reserved.