按字典顺序生成从 1 到 n 的二进制数的算法
有没有有效的算法可以做到这一点,我尝试过生成所有二进制数并将它们存储在数组中然后对它们进行排序,如果我们可以直接按字典顺序生成二进制数,代码会快得多。 例如:n=7 产生 1,10,100,101,11,110,111
Is there any efficient algorithm to do so ,I have tried to produce all binary numbers and store them in an array then sort them, if we can directly generate the binary numbers in lexicographical order the code will be much faster.
For eg : n=7 produces 1,10,100,101,11,110,111
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的关键属性是,
0
始终位于1
之前,因此您可以使用递归来解决这个问题。该算法如下所示:1
开始递归n
,忽略它recursion(curr_number + "0")
和recursion(curr_number + "1")
这是一个简单的算法,可以在大多数语言中轻松实现。
编辑:Python实现:
The key property here is,
0
will always come before1
, so you can use recursion to solve this. The algorithm would look like:1
n
, ignore itrecursion(curr_number + "0")
andrecursion(curr_number + "1")
This is a simple algorithm, which can be easily implemented in most languages.
Edit: Python implementation:
如果将完整二叉树逐行编号,从 1 到 2^d-1,按字典顺序枚举节点就是前序遍历。现在,由于节点的两个子节点携带父节点的值,后跟 0 或 1,因此我们有了递归枚举
(您还可以通过连接 0 或 1 来获得二进制表示形式。)
If you number a complete binary tree row by row, from 1 to 2^d-1, the enumeration of the nodes in lexicographical order is the preorder traversal. Now as the two children of a node carry the value of the parent followed by 0 or by 1, we have the recursive enumeration
(You can also obtain the binary representations by concatenating 0's or 1's as you go.)
您可以遵循一些规则来生成任何字符串集的字典顺序中的下一个项目:
对于对二进制字符串进行排序,这些规则很容易应用。在每次迭代中:
n
的情况下追加一个零,那么就这样做;使用按位运算符可以很容易地实现这种迭代,从而产生了这种很好的快速算法。为了简化步骤 (2),我们假设 n 为 2x-1,然后检查我们的输出:
在线尝试
通常情况下,这种迭代算法比递归算法快得多,但提出它需要对解决方案的结构有更深入的了解。
There are a few rules you can follow to generate the next item in a lexicographical ordering of any set of strings:
For ordering the binary strings, these rules are easy to apply. In each iteration:
n
, then do so;This iteration is pretty easy to implement with bitwise operators, leading to this nice quick algorithm. To simplify step (2), we assume that n is 2x-1 and just check our outputs:
Try it online
As is often the case, this iterative algorithm is a lot faster than recursive ones, but coming up with it requires a deeper understanding of the structure of the solution.