對字串中的字母進行組合

來源:互聯網
上載者:User

0 1背包問題
  先把字串去重,並記錄每個字母相應的個數.
設組合的結果為comb(s,strCount,idx,aux) ,s表示去重的字串,strCount表示對應的個數,idx表示當前位置,aux表示當前位置取了幾個數那麼
comb(s,strCount,idx,aux)= 當aux[idx]分別為0...n時comb(s,strCount,idx+1) ;

/* ============================================================================ Name        : strCombination.c Author      :  Version     : Copyright   :  Description : 對字串中的每個字母進行組合 如輸入aba 輸出:a b ab aa aab ============================================================================ */#include <stdio.h>#include <stdlib.h>#include <string.h>void pr_arrByAux(const char *s, int len,const int *aux){int i = 0, k = 0;for (i = 0; i < len; ++i){for (k = 0; k < aux[i]; ++k)printf("%c", s[i]);}printf("\n");}void pr_arr(const int *a,int len){int i=0;for(i=0;i<len;i++){printf("%d ",a[i]);}printf("\n");}//去有序字串中重複的字母,並儲存每個字母相應的個數//如      s="aabbccd"//得      s="abcd"//strCount為2,2,2,1void delRepeatAndCount(char *s,int *strCount){char *pre,*p;int i=0;if(s==NULL || strlen(s) <= 1) return;pre=s,p=s+1;for(i=0;i<strlen(s);i++){strCount[i]=1;}i=0;while(*p != '\0'){if(*p != *pre){*(++pre)=*p++;++i;}else{++p;strCount[i]++;}}*(pre+1)='\0';/*pr_arr(strCount,strlen(s));puts(s);*/}int comp(const void *pa,const void *pb){return *(char*)pa - *(char*)pb;}//s表示去重複的字母集合,strCount表示 相應字母的個數void strCombination(const char *s, int len, int *strCount, int idx, int *aux){int i = 0;if (len < 1 || idx > len)return;if (idx == len){pr_arrByAux(s, len, aux);return;}aux[idx] = 0;for (i = 0; i <= strCount[idx]; ++i){aux[idx] = i;strCombination(s, len, strCount, idx + 1, aux);}aux[idx] = 0;//還原}//對字串的字母進行組合void strComb(const char *s){//strCount 儲存字母相應的個數int *aux,*strCount ,len;char *str; //源字串的副本,並刪除其中重複的字母if(s==NULL || strlen(s) < 1) return;//initlen=strlen(s);aux=(int*)malloc(sizeof(int)*len);strCount=(int*)malloc(sizeof(int)*len);str=(char*)malloc(sizeof(char)*(len+1));strcpy(str,s);//kernelqsort(str,len,sizeof(char),comp); //變成有序字串delRepeatAndCount(str,strCount); //去重,並計數strCombination(str,strlen(str),strCount,0,aux);//組合//freefree(str);free(strCount);free(aux);}int main(void){strComb("abaa");return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.