【100题】第五十三题 字符串的全排列
生活随笔
收集整理的這篇文章主要介紹了
【100题】第五十三题 字符串的全排列
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
遞歸求解思路:
1)? 每個(gè)元素依次放到首位,然后對(duì)其余元素遞歸
2)? 當(dāng)當(dāng)前元素到達(dá)末尾的時(shí)候,輸出該序列
關(guān)鍵是:
??????每個(gè)元素交換完,之后要交換過來。每個(gè)元素依次放到首位,
??????for(int?i=currentIndex;i<=n;++i){?swap? 從i+1遞歸? swap? }
?
#include<stdio.h> #include<stdlib.h> #define SWAP(x,y,t)((t)=(x),(x)=(y),(y)=(t)) int score=0; void perm(int *list,int i,int n) {int j,temp;if(i==n){for(j=0;j<=n;j++){printf("%d ",list[j]);}printf("\n");score++;}else{for(j=i;j<=n;j++){SWAP(list[i],list[j],temp);perm(list,i+1,n);SWAP(list[i],list[j],temp);}} } int main() {int list[]={1,2,3};perm(list,0,2);printf("Thetotal number is %d\n",score);system("pause"); }?
String 版本
?
#include <iostream> using namespace std;void Permutation(string pStr, int k, int n) {if(k==n)cout<<pStr<<endl;for(int i=k;i<n;++i){swap(pStr.at(i),pStr.at(k));Permutation(pStr, k+1,n);swap(pStr.at(i),pStr.at(k));} }int main() {strings="abcdef";Permutation(s,0,s.length()); }?
二,擴(kuò)展
如果不是求字符的所有排列,而是求字符的所有組合,應(yīng)該怎么辦呢?(P72)
???
思路:這里不采用交換方式,而是采用刪減的方式。采用不同的剔除順序,并用prex保留刪減值,這樣將得到所有符合條件的序列
??
#include <iostream> using namespacestd; voidselect(string str, string prex) {string temp=str;cout<<prex<<endl;for(int i=0;i<str.length();++i){select(str.erase(i,1),prex+str.at(i));str=temp;} }int main() {string s="abcd";select(s,""); }擴(kuò)展二:
當(dāng)輸入的字符串中含有相同的字符串時(shí),相同的字符交換位置是不同的排列,但是同一個(gè)組合。
???? 舉個(gè)例子,如果輸入aaa,那么它的排列是6個(gè)aaa,但對(duì)應(yīng)的組合只有一個(gè)。
轉(zhuǎn)載于:https://www.cnblogs.com/secbook/archive/2012/08/22/2654956.html
總結(jié)
以上是生活随笔為你收集整理的【100题】第五十三题 字符串的全排列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows php的Memcache
- 下一篇: snmpd服务无法更改默认端口