从前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 }
原文地址:https://www.cnblogs.com/yfs123456/p/5402525.html