/* Definition: 1)the direction of the number,every number possesses a direction which means the direction the number tend to move. 2)active: when the number_now is active,it means that the number is greater than the number in the diretion of number_now Algorithm description: 1)finding the max active number in the array. 2)swap the max active number with the number in the direction of the max active number. 3)change the direction of the numbers which is greater the current max active number. Author: SOLIDFISH Date: 2009/10/29 */ #include <iostream> #include <string> using namespace std; #define LENGTH 100 #define LEFT -1 #define RIGHT 1 struct Node { int pos,dir; }; Node a[LENGTH]; int l; int maxActive() { int max = -1; int pos = -1; int dir = 0; int i = 0,j = 0; for( i = 0 ; i < l ; i++) { if(a[i].dir == LEFT && i > 0 && a[i].pos > a[i-1].pos && max < a[i].pos) { max = a[i].pos; pos = i; dir = LEFT; } if(a[i].dir == RIGHT && i < l - 1 && a[i].pos > a[i+1].pos && max < a[i].pos) { max = a[i].pos; pos = i; dir = RIGHT; } } if(dir == LEFT) swap(a[pos],a[pos-1]); if(dir == RIGHT) swap(a[pos],a[pos+1]); for( i = l - 1 ; i > max ; i--) { for ( j = 0 ; j < l; j++ ) if( a[j].pos == i ) { a[j].dir = -a[j].dir; break; } } return max; } int main() { string str = ""; cout<<"input the string:/n"; while(cin>>str && str != "0") { l = str.length(); int i,j,k,max; for( i = 0; i < l ; i++) { a[i].pos = i; a[i].dir = LEFT; } max = maxActive(); cout<<"===============/n"; cout<<str<<endl; while(max!=-1) { string temp = ""; for ( i = 0 ; i < l ; i++) temp+=str[a[i].pos]; temp = temp; cout<<temp<<endl; max = maxActive(); } cout<<"===============/n"; cout<<"input the string:/n"; } } /*使用递归来生成排列数*/ #include<iostream> using namespace std; template <class Type> void Swap(Type *a,Type *b) { Type temp=*a; *a=*b; *b=temp; } template<class Type> void Perm(Type list[],int k,int n) { if(k>n) { for(int i=0;i<=n;i++) { cout<<list[i]; } cout<<endl; } else { for(int i=k;i<=n;i++) { Swap(&list[i],&list[k]); Perm(list,k+1,n); Swap(&list[i],&list[k]); } } } void main() { char str[]="abc"; int k=strlen(str)-1; Perm(str,0,k); }