C语言编程练习56:彩票

题目描述

有一种彩票的玩法是从1~49这49个整数中挑选6个数字。小明为此研究出一个选号的策略,就是从这49个数字中选出一个子集S,S中包含了k(k>6)个数字,然后从S中再选择6个数字作为最终选定的号码。
你的任务是,给你k和集合S,输出从S中选择投注号码的所有组合。

输入

输入包含多组测试数据。每组输入首先是一个整数k(6<k<13)。然后是k个整数,表示集合S,这k个整数按升序给出。当k=0时,输入结束。

输出

对于每组输入,输出所有的投注组合,每行一种,每种按照号码升序排列,所有组合按照字典序升序排列。
每两组输出之间输出一个空行。

样例输入 Copy

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

样例输出 Copy

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

思路:两种方法
1.6个for循环
#include<bits/stdc++.h>
using namespace std;
int main() {
    int k,n[20],a,b,c,d,e,f;
    while(scanf("%d",&k)!=EOF) {
        for(int i=0; i<k; i++) scanf("%d",&n[i]);
        for(a=0; a<=k-6; a++) {
            for(b=a+1; b<=k-5; b++) {
                for(c=b+1; c<=k-4; c++) {
                    for(d=c+1; d<=k-3; d++) {
                        for(e=d+1; e<=k-2; e++) {
                            for(f=e+1; f<=k-1; f++) {
                                printf("%d %d %d %d %d %d\n",n[a],n[b],n[c],n[d],n[e],n[f]);
                            }
                        }
                    }
                }
            }
        }
        printf("\n");
    }
    return 0;
}

 2.递归

#include <iostream>
#include <cstdio>
using namespace std;
 
int k;
int a[50],b[7];
 
void dfs(int cur,int s)
{
    b[cur]=s;
    if(cur==6)
    {
        for(int i=1;i<=6;i++)
        {
            if(i!=6)
                cout<<b[i]<<" ";
            else
                cout<<b[i]<<endl;
        }
        return;
    }
    for(int i=cur+1;i<=k-6+1+cur;i++)
    {
        if(i<=k && a[i]>s)
            dfs(1+cur,a[i]);
    }
}
 
int main()
{
    int coun=0;
    while(cin>>k && k)
    {
        if(coun>0) cout<<endl;
        coun++;
        for(int i=1;i<=k;i++) cin>>a[i];
        for(int i=1;i<=k-6+1;i++)
        {
            dfs(1,a[i]);
        }
    }
    return 0;
}

 代码:https://blog.csdn.net/eseszb/article/details/70832345

 
上一篇:第56天学习打卡(初识Mysql及安装)


下一篇:关于网络适配器中Windows仍在设置此设备的类配置(代码56)解决办法