生成大小为k的所有子集从一组 [英] generate all subsets of size k from a set

查看:265
本文介绍了生成大小为k的所有子集从一组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要生成大小为k的所有子集从一组。

I want to generate all the subsets of size k from a set.

例如:-say我有一组6片,我必须列出所有的子集,其中的元素的基数是3

eg:-say I have a set of 6 elements, I have to list all the subsets in which the cardinality of elements is 3.

我试图寻找解决方案,但这些都是code片段。 它是长久以来我做了编码,所以我觉得很难理解code和围绕它建立一个可执行程序。

I tried looking for solution,but those are code snippets. Its been long since I have done coding,so I find it hard to understand the code and construct a executable program around it.

在C或C ++将是非常有帮助的一个完整的可执行程序。 希望最佳的解决方案使用递归的。

A complete executable program in C or C++ will be quite helpful. Hoping of an optimal solution using recursion.

推荐答案

初始化位阵列(1<< NBITS)-1 ,然后用这个算法:

Initialize a bit array with (1<<nbits)-1 and then use this algorithm:

<一个href="http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation">http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation

有关套比的最大整数大小,你仍然可以使用相同的算法,以你自己的类型。

For sets larger than the maximum integer size, you can still apply the same algorithm to your own type.

这篇关于生成大小为k的所有子集从一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆