DFS(6)——hdu1342Lotto

一、题目回顾

题目链接:Lotto

 

Sample Input
7 1 2 3 4 5 6 7
8 1 2 3 5 8 13 21 34
0
Sample Output
1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 6 7
1 2 3 5 6 7
1 2 4 5 6 7
1 3 4 5 6 7
2 3 4 5 6 7

1 2 3 5 8 13
1 2 3 5 8 21
1 2 3 5 8 34
1 2 3 5 13 21
1 2 3 5 13 34
1 2 3 5 21 34
1 2 3 8 13 21
1 2 3 8 13 34
1 2 3 8 21 34
1 2 3 13 21 34
1 2 5 8 13 21
1 2 5 8 13 34
1 2 5 8 21 34
1 2 5 13 21 34
1 2 8 13 21 34
1 3 5 8 13 21
1 3 5 8 13 34
1 3 5 8 21 34
1 3 5 13 21 34
1 3 8 13 21 34
1 5 8 13 21 34
2 3 5 8 13 21
2 3 5 8 13 34
2 3 5 8 21 34
2 3 5 13 21 34
2 3 8 13 21 34
2 5 8 13 21 34
3 5 8 13 21 34

题意:以升序的形式给定k个数,输出从中挑选6个数满足升序的所有情况。

 

二、解题思路

  • 两个参数,第一个保存当前搜索的位置,第二个保存已挑选的个数。

 

三、代码

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 using namespace std;
 6 const int maxn = 1e4+10;
 7 #define INF 0x3f3f3f3f
 8 int a[50];                //子集S 
 9 int b[10];                //存放6个数 
10 int k;                         
11 bool vis[50];
12 
13 void dfs(int pos,int num)
14 {
15     if(num==6){
16         for(int i=0;i<5;i++)    printf("%d ",b[i]);
17         printf("%d\n",b[5]);
18         return;
19     }
20     for(int i=pos;i<k;i++){
21         if(!vis[i]){
22             vis[i] = 1;
23             b[num] = a[i];
24             dfs(i+1,num+1);
25             vis[i] = 0;                    //方便下一次序列继续使用 
26         }
27     }
28     
29 }
30 int main()
31 {
32     int kase = 0;
33     while(cin>>k && !(k==0)){
34         if(kase++)    printf("\n");        //打印空行 
35         for(int i=0;i<k;i++){            //从0开始 
36             scanf("%d",&a[i]);
37         }
38         memset(vis,0,sizeof(vis));
39         dfs(0,0);
40     }
41     return 0;
42 }

 

posted @ 2017-08-08 13:04  GGBeng  阅读(188)  评论(0编辑  收藏  举报