如何生成数组中所有可能的值,其中 [x] >= [x+1]?
我正在尝试编写一个算法,该算法采用大小为 n 的数组,并生成最大大小为 max 的整数值的所有可能组合,其中位置 x 的数字大于或等于 x+1。
因此,对于大小为 4 且最大值为 5 的数组:
{0, 0, 0, 0}
{4, 3, 2, 1}
{2, 2, 0, 0}
{5, 5, 5, 5}
都是可接受的值。
{0, 1, 2, 3}
{0, 3, 0, 0}
{6, 6, 6, 6}
均无效。
对于大小为 4 且最大值为 1 的数组,这将是所有可能的组合:
{0, 0, 0, 0}
{1, 0, 0, 0}
{1, 1, 0, 0}
{1, 1, 1, 0}
{1, 1, 1, 1}
我似乎无法理解如何为任何最大值实现它。所以我问你们是否可以帮我一下:D
这些系列有名字吗?
I'm attempting to write an algorithm that takes an array of size n and generating all possible combinations of integer values up to size max where the number in position x is greater than or equal to x+1.
So for an array of size 4 and max of 5:
{0, 0, 0, 0}
{4, 3, 2, 1}
{2, 2, 0, 0}
{5, 5, 5, 5}
Are all acceptable values.
{0, 1, 2, 3}
{0, 3, 0, 0}
{6, 6, 6, 6}
Are invalid.
For an array of size 4 and max of 1 this would be all the possible combinations:
{0, 0, 0, 0}
{1, 0, 0, 0}
{1, 1, 0, 0}
{1, 1, 1, 0}
{1, 1, 1, 1}
I just can't seem to get my head around how to implement it for any value for max. So I'm asking you guys if you could give me a hand :D
Is there a name for these series?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我已经解决了,不需要递归。
我正在为其他正在寻找我所问问题答案的人发布答案。
它迭代整个数组并找到最小值的第一次出现。该值增加 1,并将其后的所有值重置为零。
I worked it out, no recursion necessary.
I'm posting the answer for anyone else who's looking for the answer for the question I asked.
It iterates through the entire array and finds the first occurance of the smallest value. That value is incremented by one and resets all values after it to zero.
你哪里有问题?提示:递归是您的朋友(您可以将递归用于嵌套循环,其中嵌套级别仅在运行时确定)。
Where are you having problems? Hint: recursion is your friend (you can use recursion for nested loops where the nesting level is determined only at runtime).
有一个接受 n 和 max 并返回一组数组的子例程。
如果n> 1,它用 n-1 递归调用自身,并且对于递归调用返回的每个结果,生成一个或多个数组,其中附加的最左边元素在前一个最左边元素和 max 之间变化。
如果 n 为 1,则返回 max+1 个 1 元素数组,其中包含从 0 到 max 的值。
Have a subroutine that takes n and max and returns a set of arrays.
If n > 1, it calls itself recursively with n-1 instead, and for each result the recursive call returned, generates one or more arrays with an additional leftmost element varying between the previous leftmost element and max.
If n is 1, it returns max+1 1-element arrays containing values from 0 to max.