字典序生成算法例子,时间复杂度为n^2
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 6 char *words ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 7 char *ptr[62] = {0}; 8 9 10 void print_words() 11 { 12 int idx = sizeof(ptr)/sizeof(*ptr); 13 while(--idx >= 0) 14 { 15 if(ptr[idx]) 16 printf("%c", ptr[idx][0]); 17 } 18 printf("\n"); 19 } 20 21 22 23 void mv_ptr() 24 { 25 int idx = sizeof(ptr) /sizeof(*ptr); 26 int mark = 1; 27 while(--idx >= 0) 28 { 29 if (ptr[idx] == NULL) 30 { 31 if (mark) 32 { 33 ptr[idx] = &words[strlen(words) - 1]; 34 mark = 0; 35 } 36 continue; 37 } 38 39 if (mark) 40 { 41 if (ptr[idx] == &words[0]) 42 { 43 ptr[idx] = &words[strlen(words) - 1]; 44 } 45 else 46 { 47 ptr[idx]--; 48 mark = 0; 49 } 50 } 51 52 } 53 } 54 int _test_ptr() 55 { 56 int idx = sizeof(ptr)/sizeof(*ptr); 57 while( --idx >= 0) 58 { 59 if (ptr[idx] != &words[0]) 60 { 61 return 0; 62 } 63 } 64 return 1; 65 } 66 int main() 67 { 68 ptr[61] = &words[strlen(words)]; 69 while(1) 70 { 71 mv_ptr(); 72 print_words(); 73 if (_test_ptr()) 74 { 75 break; 76 } 77 } 78 79 return 0; 80 }
突然来的灵感,为了写想法,变量函数名取得很糟糕!
期待哪位大神有更好的算法!!!
学一点,收获一点。学到的都是自己的!
浙公网安备 33010602011771号