next_Permutation 全排列

递归版本:(next_Permutation 全排列)
(非重复的全排列)

#include<cstdio>
#include<iostream>
using namespace std;
#include<cstring>


const int maxn=1005;
char a[maxn];

int ans=0;
bool value_Pre_Solve[maxn][maxn];
template<class value_Type> void _swap(value_Type & temp_1,value_Type & temp_2){
    value_Type temp_3=temp_1;
    temp_1=temp_2;
    temp_2=temp_3;
}
template<class value_Type> bool isTrue(value_Type find_Value,int st,int aim){
    for(int i=st;i<aim;i++){
        if(find_Value==a[i])
            return false;
    }
    return true;
}
void dfs(int k,int n){
    if(k>=n){
        cout<<"ans="<<ans<<'\t';
        cout<<a<<endl;
        ans++;
        return;
    }
    else{
        for(int i=k;i<n;i++){
            if(isTrue(a[i],k,i)){
                _swap(a[i],a[k]);
                dfs(k+1,n);
                _swap(a[i],a[k]);
            }
        }
    }
}
int main(){
    while(1){
        cin>>a;
        ans=1;
        dfs(0,strlen(a));
    }
    return 0;
}

非递归版本:(next_Permutation 全排列)

#include<cstdio>
#include<iostream>
using namespace std;
#include<algorithm>
#include<cstring>

const int maxn=1005;
const int inf=0x3f3f3f3f;
char a[maxn];

template<class value_Type> inline void _swap(value_Type & _f1,value_Type & _f2){
    value_Type _f3=_f1;
    _f1=_f2;
    _f2=_f3;
}
void reverse(int st,int aim){
    while(st<aim){
        _swap(a[st++],a[aim--]);
    }
}
bool next_f_(int a_len){
    int pos=inf;
    for(int i=a_len-1;i>=1;i--){
        if(a[i-1]<a[i]){
            pos=i-1;break;
        }
    }
    if(!(pos^inf))return false;
    int f_pos=inf,minn=a[pos];
    for(int i=a_len;i>pos;i--){
        if(a[i]>minn){
            minn=a[i];
            f_pos=i;break;
        }
    } 
    _swap(a[f_pos],a[pos]);
    reverse(pos+1,a_len-1);

    return true;
}
int main(){
    while(cin>>a){
        int len_a=strlen(a);
        //sort(a,a+len_a);
        do{


            cout<<a<<endl;
        }while(next_f_(len_a));
        printf("TM没有下一个排列了兄弟!\n");
    }
    return 0;
}

你可能感兴趣的:(next_Permutation 全排列)