算法以m 1s获取每一个二进制长度n的二进制数
我正在寻找一种快速的方法来生成每个长度n
的二进制数,其中包含m
1s。
因此,例如,如果n = 3,m = 2
,则只是:110,011,101
。
幼稚的方法是通过1
和2^n -1
之间的数字进行迭代,检查每个值的二进制表示是否包含m
1s。另外,使用一些算法来获取m
1s和n -m
0s的每种组合。
但是,我想知道是否有更快的方法可以使用位运算符进行此操作,或者可能在其二进制表示中具有m
1s的数字属性可以被利用。
I'm looking for a quick way to generate every binary number of length n
which contains m
1s.
So for example, if n=3, m=2
, this would just be: 110, 011, 101
.
The naive approach would be to iterate through numbers between 1
and 2^n - 1
, checking if each value's binary representation contains m
1s. Alternatively, using some algorithm to get each combination of m
1s and n - m
0s.
However, I'm wondering if there might be some quicker way to do this with bitwise operators, or perhaps a property of numbers with m
1s in their binary representation that could be exploited.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
- 首先您需要将“ 1”放在位置n
- 然后,您需要将M-1 1'1'放在0到N-1的位置。
- 您需要梳子(N-1,M-1)才能执行此操作,例如使用重复出现的算法(要将M-1'1'放在N-1位置,您将1放在i = n-1的位置上I-1位置的-2和M-2'1'。
-First you need to put a '1' in position n
-Then you need to put m-1 '1' in the positions 0 to n-1.
-You need Comb(n-1,m-1) to do this, for example using a recurring algorithm (to put m-1 '1' in n-1 positions you put a 1 in positions i= n-1 to m-2 and m-2 '1' in i-1 positions.
如果您只想计算所有可能的二进制数字,则答案将为NCM IE C(n,m)=(n! /(m! *(n -m)!)。请参阅此处。(有关数学概念的解释: Combination概念: Combination。)。)。)。
If you want only to count all possible binary numbers, then the answer will be nCm i.e C(n,m) = (n! / (m! * (n−m)!). See here. (for an explanation of the mathematical concept: combination.)
If you need to find all numbers, then this problem is the same as: "Find all the possible Binary strings of size n having m set bits". You can refer to this for this case.