zoukankan      html  css  js  c++  java
  • 全排列模板

    一,递归实现

    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µÄÈ«ÅÅÁÐΪ:
    ");
    26     permutation(s,0,3);
    27     char s2[]="122";
    28     printf("122µÄÈ«ÅÅÁÐΪ:
    ");
    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µÄÈ«ÅÅÁÐΪ:
    ");
    37     permutation(s,0,3);
    38     char s2[]="1233";
    39     printf("1233µÄÈ«ÅÅÁÐΪ:
    ");
    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µÄÈ«ÅÅÁÐΪ:
    ");
    20     permutation(s,3);
    21     char s2[]="1233";
    22     printf("1233µÄÈ«ÅÅÁÐΪ:
    ");
    23     permutation(s2,4);
    24     return 0;
    25 } 
    View Code

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

  • 相关阅读:
    商业智能领域需要了解的数据库优化理论
    动态监听与静态监听(转载)
    Oracle查看表结构的几种方法
    PLSQL Developer使用技巧整理
    Oracle数据库的三种验证机制
    EAV模型
    三门问题
    第一个python实例程序
    type()
    pi
  • 原文地址:https://www.cnblogs.com/L-King/p/5426597.html
Copyright © 2011-2022 走看看