經典代碼拾遺

來源:互聯網
上載者:User

 組合問題(遞迴)

#include <stdlib.h>#include <stdio.h>#include <string.h>void find(char *source, char *result, int n){if(n==1){while(*source)printf("%s%c\n", result, *source++);}else{int i, j;for(i=0; source[i] != 0; i++);for(j=0; result[j] != 0; j++);for(; i>=n; i--){result[j] = *source++;result[j+1] = '\0';find(source, result, n-1);}}}int main(int argc, char* argv[]){int const n = 3;char *source = "ABCDEk", result[n+1] = {0};if(n>0 && strlen(source)>0 && n<=strlen(source))find(source, result, 3);return getchar();}

//http://faq.csdn.net/read/191186.html 組合問題 演算法

全排列(非遞迴)

#include<stdio.h>/*這兩個庫函數是習慣性的加上去的^_^。*/#include<stdlib.h>#include <time.h>#define ISPRINT/*是否列印結果的標誌*/#define MAX 200/*最大的數*/unsigned int *_NUM;/*用於存放一條結果的數組指標*/char *_NUMFLAG;/*用於存放是否已經使用的標誌*/#define NUM(j) (*(_NUM+(j)))/*第j位的數字*/#define NUMFLAG(j) (*(_NUMFLAG+(j)))/*數字j是否已經使用的標誌,0為沒有使用,1為已經使用*/#define NUMUSE(j) (*(_NUMFLAG+(*(_NUM+(j)))))/*第j位上的數字是否已經使用的標誌,0為沒有使用,1為已 經使用*/void main(){int t1 = clock();unsigned int number,j;int i;printf("Input number=8");number = 8;//scanf("%u",&number);if((number>=MAX)||(number<=1)){puts("輸入資料錯誤。");exit(-1);}/*初始化記憶體和第一個結果*/_NUM = (unsigned int*)malloc(sizeof(unsigned int)*number);if(!_NUM){puts("分配給_NUM出現記憶體不足");exit(-1);}_NUMFLAG=(char*)malloc(sizeof(char)*number);if(!_NUMFLAG){puts("分配給_NUMFLAG出現記憶體不足");exit(-1);} for(i=0;i<number;i++){NUM(i)=i;NUMFLAG(i)=1;}/*初始化第一條結果和使用標誌*/int k;for(k=0;k<number;k++)printf("%d ",NUMFLAG(k));puts("");do/*主迴圈*/{#ifdef ISPRINT/*列印結果*/for(j=0;j<number;j++)printf("%d ",NUM(j));/*列印一條結果。*/puts("");/*並換行*/#endif  NUMUSE(number-1)=0;//置最後一位元字的使用標誌為0.for(k=0;k<number;k++)printf("%d ",NUMFLAG(k));puts("");/*在前一個結果中從後往前尋找第一個從小到大排列的數,並存放到變數j中*/for(i=number-2;i>=0;i--){NUMUSE(i)=0;if(NUM(i)<NUM(i+1))break;}if(i<0)break;/*從這裡退出主迴圈.*/for(j=NUM(i)+1;j<number;j++){if(!NUMFLAG(j))break;}NUMFLAG(j)=1;NUM(i)=j;for(j=0,i++;i<number;j++){if(!NUMFLAG(j)){NUM(i++)=j;NUMFLAG(j)=1;}}}while(1);/*釋放記憶體*/free(_NUM);free(_NUMFLAG);printf("用時%dms/n",clock()-t1);getchar();}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.