打印 y 槽中 x 对象的所有组合 (Java)
如果您有 x 个对象(可以用 1 表示)要放置在 y 个槽中(空槽可以用 0 表示),请编写一个函数来打印将对象放置在槽中的所有可能方式。该方法将对象的数量和总槽数作为输入。
例如, possibleCombinations(3, 5) 应该打印 3 个对象可以放置在 5 个槽中的方式:
11100, 11010, 11001, 10110, 10101, 10011, 01110, 01101, 01011, 00111
我已经考虑将递归作为一种选择,但我不知道该怎么走关于对其进行设置,使其适用于任意数量的对象。任何帮助将不胜感激!
If you have x objects (can be represented by 1s) that are to be placed in y slots (empty slots can be represented as 0s), write a function that prints all of the possible ways that the objects can be placed in the slots. The method will take as input the number of objects and the number of total slots.
For example, possibleCombinations(3, 5) should print the ways 3 objects can be placed in 5 slots:
11100, 11010, 11001, 10110, 10101, 10011, 01110, 01101, 01011, 00111
I've considered recursion as an option, but I'm not sure how to go about setting it up so that it works for any number of objects. Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一些伪代码,显然我没有使用非常好的数据结构。但如果可能的话,您可以查看每个调用,检查包含或不包含每个项目的情况,然后从那里继续。这是 else 语句中的一对递归调用。
Here is some pseudo code, obviously I'm not using a very good data structure. But you can see each call if possible, checks the cases where each item is either included or not included and continues from there. That's the pair of recursive calls in the else statement.
这是一些java代码:
aux() 实际上完成了工作,它完成了所有可能性:添加 0 或添加 1,并在最后仅打印那些“使用”所有可能的 1 的
编辑: 更改递归结束条件,以修剪不会在末尾打印的情况。
here is some java code:
aux() actually do the work, it does all possibilities: add 0 or add 1, and prints at the end only those who "used" all the possible 1's
EDIT : changed the recursion end condition, to trim cases that will not be printed at the end.
这提醒我您可以在 wolframalpha.com 并获得正确答案。
此答案中的步骤是:
That reminds me you can search
Permutations[Join[Table[1, {3}],Table[0, {5-3}]]]
, at wolframalpha.com and get the right answer.Steps in this answer are:
下面是我将如何执行 3、5。从字符串
111
开始。 5 - 3 = 2,因此总共添加 2 个零。每个零a1b1c1d
有四个可能的位置。 4 ^ 2 表示 16 个可能的位置,将第一个位置编码为 0 - 3,将第二个位置编码为 (0 - 3) * 4。现在枚举 0 - 15,并打印出结果组合。在这个方案中,前 5 个输出是:我们有一个重复。当您需要组合时,此机制会打印出排列。可能有一种方法可以枚举组合,但最简单的解决方案是仅对结果进行索引并确保不会两次返回相同的结果。
Here is how I would do 3, 5. Start with the string
111
. 5 - 3 = 2, so adding 2 zeros total. There are four possible locations for each zeroa1b1c1d
. 4 ^ 2 means 16 possible locations, encoding the first location as 0 - 3, and second as (0 - 3) * 4. Now enumerate 0 - 15, and print out the resulting combination. In this scheme the first 5 outputs are:And we have a repeat. This mechanism is printing out permutations when you want combinations. There is likely a way to enumerate the combination but the simplest solution is to just index your results and ensure you don't return the same one twice.