zoukankan      html  css  js  c++  java
  • 从前M个字母中取N个的无重复排列(回溯)

    转载请注明出处

    题目描述

    输出从前M个字母中取N个的无重复字母排列

    Input

    输入M N 
    1<=M=10, N<=M

    Output

    按字典序输出排列

    Sample Input

    4 2

    Sample Output

    A B
    A C
    A D
    B A
    B C
    B D
    C A
    C D
    C D
    D A
    D B
    D C 

    Hint

    要用到剪枝

     1 /**
     2     网址: http://www.codeup.cn/problem.php?id=2906
     3     题目: 从前M个字母中取N个的无重复排列[2*+]
     4 */
     5 #include <stdio.h>
     6 #include <memory.h>
     7 
     8 char s[15];
     9 char str[]={'A','B','C','D','E','F','G','H','I','J','H','L','M','N'};
    10 int M,N;
    11 int colected[15];///实时标记已入选字符
    12 int stack[15],top = 0;
    13 
    14 void print(){
    15     int i;
    16     for(i = 0; i < N - 1; i++){
    17         printf("%c ",s[i]);
    18     }
    19     printf("%c
    ",s[i]);
    20 }
    21 
    22 void dfs(int cur,int last){
    23     int i;
    24     if(cur == N){
    25         print();
    26         colected[stack[--top]] = 0;
    27         return ;
    28     }
    29 
    30     for(i = 0; i < M; i++){
    31         if(colected[i] != 1){
    32             s[cur] = str[i];
    33             stack[top++] = i;
    34             colected[i] = 1;
    35             dfs(cur + 1,i);
    36         }
    37 
    38     }
    39     if(i == M)
    40         colected[stack[--top]] = 0;
    41 }
    42 
    43 int main(void){
    44     while(scanf("%d%d",&M,&N) != EOF){
    45         dfs(0,0);
    46     }
    47     return 0;
    48 }
  • 相关阅读:
    Linux 磁盘管理
    03.线程的通知notify与等待wait
    02.线程的等待与中断
    01.线程的三种创建方式与运行
    java--ArrayList,LinkedList应用比较
    java--字符串拼接比较
    java--CharAt,StartWith
    java--split,index,StringTokenizer比较
    java--substring内存溢出问题
    java--String intern
  • 原文地址:https://www.cnblogs.com/yfs123456/p/5402525.html
Copyright © 2011-2022 走看看