//out put all the combinations of 5 input characters,less than 5 included #include<stdio.h> void try(int); //DFS function int used[5]; //to record if one charater is used char result[6]; char letters[5]; int depth; //to limit the depth of the search int main (void) { int i,j; for (i=0;i<5;i++) scanf("%c",&letters[i]); for (depth=1;depth<=5;depth++){ for (j=0;j<5;j++) used[j]=result[j]=0; try(0); } return 0; } void try(int lim) { int i; if (lim == depth) { //reach the leaf,time to output for (i=0;i<depth;i++) printf("%c%s",result[i],(i==(depth-1))?"\n":""); return; } for (i=0;i<5;i++) { if(!used[i]){ //pick an unused character used[i]=1; result[lim]=letters[i]; try(lim+1); //go deeper used[i]=0; //set back the usage state back } } }
Friday, December 14, 2007
Recalled a little bit C
It took me almost an hour to code the messy thing in C,which wouldn't take me more than 5 minutes to achieve 1 year ago.
Its basic job is to output all the possible combinations of 5 input characters, including those have less than 5 characters.
I used DFS to transverse the answer tree, and output the recorded path every time it arrived a leaf.Meantime,there's a variable to control the depth of the search increases so that we get all the combinations made up from 1 to 5 characters.
Here it is~
Labels:
Algorithms,
C,
Programming
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment