Fork me on GitHub

#include <stdio.h>
#include<string.h>
#include<queue>
#include<string>
using namespace std;
bool vis[7];
char a[7],re[7];
int len;
string ss;
queue<string> s;
void dfs(int cur)
{
   if(cur>=len)
   {
      // for(int i=0;i<len;i++)
         //  printf("%c",re[i]);
       re[len+1]='\0';
       ss.assign(re,len);
       s.push(ss);
       //printf("%s\n",re);
   }
   else
   {
       for(int i=0;i<len;i++)
       {
           if(!vis[i])
           {
               vis[i]=1;
               re[cur]=a[i];
               dfs(cur+1);
               vis[i]=0;
           }
       }
   }
}
int main()
{

    while(scanf("%s",a)!=EOF)
    {
        len=strlen(a);
        dfs(0);
        while(!s.empty())
        {
            printf("%s\n",s.front().c_str());
            s.pop();
        }
        printf("\n");
    }
    return 0;
}
更快
#include <cstdio> #include <algorithm> #include <cstring> //using namespace std; int main() { int len; char str[7]; while(scanf("%s",str)!=EOF) { puts(str); len=strlen(str); while (std::next_permutation(str, str +len )) { puts(str); } printf("\n"); } return 0; }

 

posted on 2013-02-04 19:33  huashiyiqike  阅读(352)  评论(0编辑  收藏  举报