Problem Description
In the German Lotto you have to select 6 numbers from the set {1,2,...,49}. A popular strategy to play Lotto - although it doesn‘t increase your chance of winning - is to select a subset S containing k (k > 6) of these 49 numbers, and then play several games
with choosing numbers only from S. For example, for k=8 and S = {1,2,3,5,8,13,21,34} there are 28 possible games: [1,2,3,5,8,13], [1,2,3,5,8,21], [1,2,3,5,8,34], [1,2,3,5,13,21], ... [3,5,8,13,21,34].
Your job is to write a program that reads in the number k and the set S and then prints all possible games choosing numbers only from S.
Input
The input will contain one or more test cases. Each test case consists of one line containing several integers separated from each other by spaces. The first integer on the line will be the number k (6 < k < 13). Then k integers, specifying the set S, will
follow in ascending order. Input will be terminated by a value of zero (0) for k.
Output
For each test case, print all possible games, each game on one line. The numbers of each game have to be sorted in ascending order and separated from each other by exactly one space. The games themselves have to be sorted lexicographically, that means sorted
by the lowest number first, then by the second lowest and so on, as demonstrated in the sample output below. The test cases have to be separated from each other by exactly one blank line. Do not put a blank line after the last test case.
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
下面我来讲讲全排列问题吧!
把筛选出来的数用一个数组存起来,其实深搜就是递归回溯,当不满足条件是返回到上一层,这个全排列也是一样,当筛选完了之后输出结果,没选到则再次回溯,我的理解就是返回到上一层,接着筛选,全排列,最小步数等问题,回溯之后要把标记是否访问过的数组还原成原样,因为其他方式也可以走到那一步。
这种题目以及N皇后问题都有一个固定的套路,可以说是个模板:
有一个判断,判断是否接着往下走(即递归),有一个最后是否找到一个方式的判断条件,找到了输出,没找到就回溯,写代码确实很简单,但相同确实不简单,我昨天痛苦的照着别人的代码写N皇后问题,似懂非懂,今天也做了不少题了,了解了这种题目的做法,就是一直往下找,知道找到满足条件的方式,找到了也会回溯,递归就像栈一样,一开始一直往里面放东西,即一直递归,你要跳出来是也是一层一层跳出来的。
#include<stdio.h> #include<string.h> int a[10100]; int select[7]; bool vis[10010]; int n; void DFS(int c) { if(c==7)//c==7时刚好选出6个数 { for(int i=1;i<=6;++i) printf("%d ",select[i]); printf("\n"); } for(int i=1;i<=n;++i) { if(a[i]>=select[c-1]&&!vis[a[i]]) { select[c]=a[i]; vis[a[i]]=1; DFS(c+1); vis[a[i]]=0; } } } int main() { while(~scanf("%d",&n),n) { memset(select,0,sizeof(select)); memset(vis,0,sizeof(vis)); for(int i=1;i<=n;++i) { scanf("%d",a+i); } DFS(1); printf("\n"); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。