您的位置:首页 > 其它

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

2011-12-19 14:16 543 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐