【100题】第五十三题 字符串的全排列
生活随笔
收集整理的這篇文章主要介紹了
【100题】第五十三题 字符串的全排列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
遞歸求解思路:
1)? 每個元素依次放到首位,然后對其余元素遞歸
2)? 當當前元素到達末尾的時候,輸出該序列
關鍵是:
??????每個元素交換完,之后要交換過來。每個元素依次放到首位,
??????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()); }?
二,擴展
如果不是求字符的所有排列,而是求字符的所有組合,應該怎么辦呢?(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,""); }擴展二:
當輸入的字符串中含有相同的字符串時,相同的字符交換位置是不同的排列,但是同一個組合。
???? 舉個例子,如果輸入aaa,那么它的排列是6個aaa,但對應的組合只有一個。
轉載于:https://www.cnblogs.com/secbook/archive/2012/08/22/2654956.html
總結
以上是生活随笔為你收集整理的【100题】第五十三题 字符串的全排列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows php的Memcache
- 下一篇: snmpd服务无法更改默认端口