关于输出给定数组的k大小的子集

来源:互联网 发布:许知远 陈嘉映 知乎 编辑:程序博客网 时间:2024/05/01 14:22

给定一个长度为M的数组(元素不重复),求出其给定大小为K的所有子集。

c语言程序如下:

   算法:采用递归的思想(这个是从别人那里抄来的 (*^__^*) 嘻嘻……)

#include<stdio.h>

#include<malloc.h>

#define M 10

#define K 2

int count=0;//记录总共产生了多少个子集

void get_subsets(intarrays[],int *tem, intarrays_start,int tem_length){

   int i=0;

   if(tem_length==K){

      for(i=0;i<K;i++){

         printf("%d",tem[i]);}printf("\n");//输出产生的子集

      count++;

   }

   else if(M-arrays_start>=(K-tem_length)){//控制是否可以进行本次递归

   tem[tem_length]=arrays[arrays_start];//将本次探测的array值加入子集

   get_subsets(arrays,tem,arrays_start+1,tem_length+1);//子集长度减1再递归

   if(M-arrays_start-1>=(K-tem_length)){ //是否可跳过本次array值重新递归

   get_subsets(arrays,tem,arrays_start+1,tem_length);//进行下一个array值的递归查询

       }}}

void main(){

   int arrays[M]={2,5,8,1,6,7,11,14,0,3};

   int *tem=(int*)malloc(sizeof(int)*K);

   free(tem);

   get_subsets(arrays,tem,0,0);

   printf("There are %d subsets\n",count);

printf("finished\n");}

程序中的M和K都是预先知道的,在main函数中的arrays数组中存放元数组。
原创粉丝点击