• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
L&King
有何不可!
   首页    新随笔    联系   管理    订阅  订阅

全排列模板

一,递归实现

1,不去重

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 using namespace std;
 5 void permutation(char *s,int d,int l)
 6 {
 7     if(d==l-1)
 8     {
 9         puts(s);
10         return ;
11     }
12     else
13     {
14         for(int i=d;i<l;i++)
15         {
16             swap(s[i],s[d]);
17             permutation(s,d+1,l);
18             swap(s[i],s[d]);
19         }
20     }
21 }
22 int main() 
23 {
24     char s[]="123";
25     printf("123µÄÈ«ÅÅÁÐΪ:\n");
26     permutation(s,0,3);
27     char s2[]="122";
28     printf("122µÄÈ«ÅÅÁÐΪ:\n");
29     permutation(s2,0,3);
30     return 0;
31 }
View Code

2,去重

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 using namespace std;
 5 bool pd(char *s,int l,int r)
 6 {
 7     for(int i=l;i<r;i++)
 8         if(s[i]==s[r])
 9             return false;
10     return true;
11 }
12 void permutation(char *s,int d,int l)
13 {
14     if(d==l-1)
15     {
16         puts(s);
17         return ;
18     }
19     else
20     {
21         for(int i=d;i<l;i++)
22         {
23             if(pd(s,d,i))
24             {
25                 swap(s[i],s[d]);
26                 permutation(s,d+1,l);
27                 swap(s[i],s[d]);
28             }
29             
30         }
31     }
32 }
33 int main() 
34 {
35     char s[]="123";
36     printf("123µÄÈ«ÅÅÁÐΪ:\n");
37     permutation(s,0,3);
38     char s2[]="1233";
39     printf("1233µÄÈ«ÅÅÁÐΪ:\n");
40     permutation(s2,0,4);
41     return 0;
42 }
View Code

二,STL实现(去重)

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<algorithm>
 5 using namespace std;
 6 void permutation(char *s,int l)
 7 {
 8     sort(s,s+l);
 9     do
10     {
11         for(int i=0;i<l;i++)
12             putchar(s[i]);
13         puts("");
14     }while(next_permutation(s,s+l));
15 }
16 int main()
17 {
18     char s[]="123";
19     printf("123µÄÈ«ÅÅÁÐΪ:\n");
20     permutation(s,3);
21     char s2[]="1233";
22     printf("1233µÄÈ«ÅÅÁÐΪ:\n");
23     permutation(s2,4);
24     return 0;
25 } 
View Code

 参考文章:http://blog.csdn.net/hackbuteer1/article/details/6657435

posted @ 2016-04-24 11:25  L&King  阅读(210)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3