zoukankan      html  css  js  c++  java
  • 枚举排列模板、

     1 //生成1~n的排列,按字典序由小到大排列
     2 void print_permutation(int n,int* A,int cur)
     3 {
     4     if(cur==n){            //递归边界                    
     5         for(int i=0;i<n;++i)    printf("%d",A[i]);
     6         printf("
    ");
     7     }
     8     else
     9         for(int i=1;i<=n;++i){        //尝试在A[cur]中填各种数字i 
    10             int ok=1;
    11             for(int j=0;j<cur;++j)
    12                 if(A[j]==i)    ok=0;    //如果i已经在A[0]~A[cur-1]出现过,则不能在选了 
    13             if(ok){
    14                 A[cur]=i;                        
    15                 print_permutation(n,A,cur+1);    //递归调用 
    16             }
    17         }
    18 } 
     1 //枚举所有排列的另一个方法是从字典序最小排列开始,不停的调用“求下一个排列”的过程
     2 //c++stl中提供了一个库函数next_permutation
     3 #include<cstdio>
     4 #include<algorithm>
     5 using namespace std;
     6 int main()
     7 {
     8     int n,p[10];
     9     scanf("%d",&n);
    10     for(int i=0;i<n;++i)    scanf("%d",&p[i]);
    11     sort(p,p+n);                    //排序得到最小字典序的排列 
    12     do{
    13         for(int i=0;i<n;++i)    printf("%d",p[i]);    //输出排列p 
    14         printf("
    ");
    15     }while(next_permutation(p,p+n));    //求下一个排列 
    16 }
    17 //上述代码同样适用于可重集、
  • 相关阅读:
    c中的数组与字符串
    c中的函数
    C中的流程控制
    c中的基本运算
    scanf函数
    c中的数据类型、常量、变量
    c中的关键字、标识符、注释
    ios必须知道的事情
    安卓开发之获取SD卡空间数据
    安卓日志猫的使用
  • 原文地址:https://www.cnblogs.com/sasuke-/p/5181157.html
Copyright © 2011-2022 走看看