{1,...,n}的所有k个元素子集的格雷码

编程入门 行业动态 更新时间:2024-10-10 02:19:40
本文介绍了{1,...,n}的所有k个元素子集的格雷码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种迭代n个元素集的所有k个元素子集的算法.我不想显式地生成所有这些子集.

I am seeking for an algorithm which iterates through all k element subsets of an n element set. I do not want to generate all those subset explicitly.

有一个简单的算法可以做到这一点,即按字典顺序对相应的位向量进行排序,然后从当前子集转到下一个子集.

There is an easy algorithm to do this, namely sorting the corresponding bit vectors lexographically and then go from the current subset to the next one.

尽管如此,我仍在寻找一种算法,该算法在每个步骤中仅切换2位.我已经读过这样的代码称为灰色代码",但是我没有找到解决我的问题的算法.

Nevertheless, I seek for an algorithm which only switches 2 bits in each step. I have read that such a code is a called "gray-code" but I did not found an algorithm for my problem.

是否有直接的实现方法?

Is there a straight forward implementation for this?

推荐答案

这不会是一个完整的答案,但也不会包含在注释中.

This isn't going to be a complete answer, but it's also not going to fit in a comment.

与格雷码的关系就是您所需要的镜像.每次格雷码设置一个新位时,它下面的所有位都从该点开始向后向后前进(直到该位被清除或高于该位使反向反转为止).

The relationship to gray code that you need is the mirroring. Every time gray code sets a new bit, all the bits below it progress backwards from that point on (until that bit is cleared or a bit above that reverses the reversal).

要按照字典顺序重现此顺序,您需要反转每次交换后对其余位进行迭代的顺序.

To reproduce this with your lexicographic ordering you need to invert the order in which you iterate through the remaining bits after each swap.

您也许可以将其实现为迭代转换,以常规顺序进行,并在每次遇到从1到0的转换时重复反转其余位的顺序.

You might be able to implement this as an iterative transformation, taking your regular ordering and repeatedly reversing the order of the remaining bits every time you encounter a transition from 1 to 0.

更多推荐

{1,...,n}的所有k个元素子集的格雷码

本文发布于:2023-11-29 09:35:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子集   格雷   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!