Given an array of size n, find all the possible sub set of the array of size k

Given an array of size n, find all the possible sub set of the array of size k(all the subsets must be of size k).

Q:

给一个大小为n的数组,输出其中k个数字的组合。

A:

void subarray(int arr[], int t[], int n, int index, int k, int kIndex) 
{
int i;

if (n == 0)
return;

if (kIndex == k) { // 说明已经取到了k个数字,打印出来
for (i = 0; i < kIndex; i++)
printf("%d ", t[i]);
printf("\n");
return;
}

if (n - index < k - kIndex)
return;

t[kIndex] = arr[index];
subarray(arr, t, n, index + 1, k, kIndex + 1); // 已经取了当前的数字,再继续取;

subarray(arr, t, n, index + 1, k, kIndex); // 因为k <= n,所以存在有无法取到的数字,该调用则是忽略前面的数字,从后面的数字开始取
}

for example: 

    int att1[5] = {1,2,3,4,5};
int att3[5] = {};
subarray(att1, att3, 5, 0, 4, 0);





posted @ 2011-12-19 14:16  百分百好牛  阅读(326)  评论(0编辑  收藏  举报