生成所有具有重复数字的组合
我已经阅读这个网站足够长的时间了,知道不要隐瞒这是一项家庭作业。但我正在尝试编写一个代码,可以生成仅由 0 和 1 组成的字符串的所有可能组合。如果字符串的长度是n^2,那么就会有n个1,其余的都是0。长度始终是完全平方数。我正在用 C 进行编码,我一直在尝试在嵌套循环中完成它,但似乎可以通过递归方式更轻松地完成它,我只是不确定如何进行设置。任何提示或建议将不胜感激。
I've been reading this site long enough to know not to hide that this is a homework assignment. But I am trying to write a code that can generate all possible combinations of a string of only 0's and 1's. If the length of the string is n^2, then there will be n 1's and the rest will be 0's. The length is always a perfect square. I am coding in C and I have been trying to do it in nested loops but it seems like it could be done more easily in a recursive manner, I'm just not sure how to get that set up. Any tips or advice would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
伪代码:
pseudocode:
我不确定这个问题是否适合递归。在 C(和大多数语言)中,每次调用函数时,都会创建一个堆栈帧并使用几个处理器周期和一块堆栈内存。此问题的任何递归解决方案都会创建 n^2 堆栈帧,即使递归本身仅添加一位信息。
下面概述了一个非常糟糕的解决方案。它不做什么:
...但它可能会让您了解基本模式。
I'm not sure that this problem lends itself to recursion. In C (and most languages), every time you call a function you create a stack frame and use a few processor cycles and a chunk of stack memory. Any recursive solution to this problem will create n^2 stack frames, even the the recursion itself is only adding one bit of information.
A really bad solution is outlined below. What it doesn't do:
...but it might give you an idea of the basic pattern.
对问题进行递归建模的关键是将问题的较大版本分解为与同一问题的较小版本相结合的简单计算,以及终止递归的简单情况。
在这种情况下,问题是:
您可以将其分解为:
M = 0
,则输出一个空字符串;否则M-1
且恰好包含N
1 的所有字符串,每个字符串都以 0 为前缀;如果N > 0
,然后输出长度为M-1
且正好包含N-1
1 的字符串,每个字符串都以 1 为前缀。这里,
M = 0
是终止递归的简单情况。将以上内容转化为代码相当简单。The key to modelling a problem recursively is to break a larger version of the problem into a simple calculation combined with a smaller version of the same problem, and a trivial case that terminates the recursion.
In this case, the problem is:
You can break this down into:
M = 0
, then output an empty string; otherwiseM-1
that contain exactlyN
1s, prefixing each with an 0; andN > 0
, then output all strings of lengthM-1
that contain exactlyN-1
1s, prefixing each with a 1.Here,
M = 0
is the trivial case that terminates the recursion. Turning the above into code is reasonably simple.