排列问题

来源:互联网 发布:mac更新flash插件 编辑:程序博客网 时间:2024/06/08 06:16
//参考博客:http://blog.csdn.net/yoer77/article/details/53458612http://blog.csdn.net/cpfeed/article/details/7376132http://blog.csdn.net/morewindows/article/details/7370155//* 递归+回溯(未去重) */#include <iostream>#include <cstring>using namespace std;void Perm(char s[],int k,int n){    if(k == n-1)    {        for(int i = 0; i < n ;i++)            cout<<s[i];        cout<<endl;;    }    else    {        for(int i = k ; i < n; i++)        {            swap(s[k],s[i]);            Perm(s,k+1,n);            swap(s[k],s[i]);        }    }}int main(){    char s[] = "123";    int len = strlen(s);    Perm(s,0,len);    return 0;}/* 递归+回溯(去重) */#include <iostream>#include <cstring>using namespace std;int count = 0;bool IsSwap(char s[],int l,int r){    for(int i = l ; i < r; i++)    {        if(s[i] == s[r])            return false;    }    return true;}void Perm(char s[],int k,int n){    if(k == n-1)    {        for(int i = 0; i < n; i++)            cout<<s[i];        count++;        cout<<endl;    }    else    {        for(int i = k; i < n; i++)        {            if(IsSwap(s,k,i))            {                swap(s[k],s[i]);                Perm(s,k+1,n);                swap(s[k],s[i]);            }        }    }}int main(){    char s[] = "1232";    int len = strlen(s);    Perm(s,0,len);    cout<<count<<endl;    return 0;}/* dfs深搜(未去重) */#include <iostream>#include <cstring>using namespace std;#define maxn 100char perm[maxn];int visit[maxn];char s[] = "abcd";int count = 0;void dfs(int step,int n){    if(step == n)    {        for(int i = 0; i < n; i++)            cout<<s[perm[i]];        count++;        cout<<endl;    }    else    {        for(int i = 0; i < n; i++)        {            if(!visit[i])            {                perm[step] = i;                visit[i] = 1;                dfs(step+1,n);                visit[i] = 0;            }        }    }}int main(){    int n = strlen(s);    memset(perm,0,sizeof(perm));    memset(perm,0,sizeof(visit));    dfs(0,n);    cout<<count<<endl;    return 0;}/* 字典序 */#include <iostream>#include <cstring>using namespace std;void Reverse(char *i,char *j){    while(i < j)    {        swap(*i,*j);        i++; j--;    }}bool Next_permutation(char s[]){    int len = strlen(s);    if(!len) return false;    char *pEnd,*p,*q,*pFind;    pEnd = s + len-1;    p = pEnd;    while(p != s)    {        q = p;        p--;        while(*p < *q)        {            pFind = pEnd;            if(*pFind < *p)                pFind--;            swap(*p,*pFind);            Reverse(q,pEnd);            return true;        }    }    Reverse(s,pEnd);    return false;}int main(){    char s[] = "123";    do    {        cout<<s<<endl;    }while(Next_permutation(s));    return 0;}