【问题标题】:Generate all lists of size n, such that each element is between 0 and m (inclusive)生成所有大小为 n 的列表,使得每个元素都介于 0 和 m(含)之间
【发布时间】:2012-12-21 23:00:09
【问题描述】:

生成所有大小为n 的列表,使得每个元素都介于0 和m(含)之间。

(m+1)^n这样的列表。

【问题讨论】:

  • 你已经尝试过什么方法来解决这个问题?
  • 有了这个特定的限制,它就像以前一样容易,特别是因为大多数语言在它们的本地库中都有八进制。
  • 我不确定您真正在寻找什么。但是根据您写的内容,我看不出您为什么不使用 6 个嵌套循环,仅此而已。我错过了什么吗?
  • 你试过什么。这是一个非常琐碎的问题。尤其是没有限制。
  • 更正:有(m+1)^n这样的列表。

标签: algorithm list language-agnostic combinatorics exponent


【解决方案1】:

编写一般情况有两种简单的方法。一个在@didierc 的现有答案中进行了描述。另一种方法是递归。

例如,考虑一个将字符串作为参数的方法:

if(input string is long enough)
  print or store it
else
  iterate over digit range
    recursive call with the digit appended to the string

【讨论】:

  • 我想我实际上比我更喜欢你的解决方案。
【解决方案2】:

这就像枚举 n 位数的基数 (m+1) 中的所有数字。

start with a list of n zeros
do the following loop
    yeld the list as a new answer
    increment the first element, counting in base (m+1), and propagate the carry recursively on its next element
    if there is a carry left, exit the loop

更新: 只是为了好玩,如果我们添加所有数字必须保持不同的限制(就像最初所说的彩票号码 - 当然我们假设 m >= n),那么解决方案是什么?

我们继续枚举所有具有上述限制的数字,并且任何元素都必须大于列表中的后继元素(即等级k < n的数字大于等级k+1的数字) . 这是通过在计算进位时简单地检查当前数字不会等于其前任数字来实现的,如果是,则进一步传播进位。

然后,对于通过枚举产生的每个列表,计算所有可能的排列。有已知的算法可以执行该操作 计算,例如参见Johnson-Trotter algorithm,但可以构建一种更简单的递归算法:

 function select l r:
   if the list r is empty, yeld l
   else
     for each element x of the list r
        let l' be the list of x and l
        and r' the remaining elements of r
        call select l' r'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多