【问题标题】:Generating all lexicographical permutations without comparisons of elements生成所有字典排列而不比较元素
【发布时间】:2015-01-11 20:12:55
【问题描述】:

当我有一个给定的序列 s=(a,b,c,d,e...) - 以非递减顺序排序时,我遇到了问题。我的工作是开发一种算法,该算法将按字典顺序生成所有可能的排列 - 以反转的 s(最高顺序)结束。

诀窍是:我无法将任何两个元素相互比较。无论元素值如何,所有操作都必须“自动”完成。

【问题讨论】:

  • 要么需要比较元素来判断哪些相等,要么必须允许输出重复的字符串。
  • 好的,然后逐步遍历 1..n 的排列,并且仅在输出时将排列应用于 s。但也许这违反了这个问题的精神。为什么会有这种限制?
  • 好的,我输出重复的字符串,以防s中有相等的元素。
  • @harold :我不明白你的解决方案......你能更准确吗?
  • @maciek 在一个额外的数组中生成 1..n 的所有排列,您可以按照标准方式执行此操作,因为不涉及 s 中的元素,因此不适用比较限制。然后对于每一个排列,用它来构造来自s的元素的对应排列。

标签: algorithm permutation discrete-mathematics lexicographic


【解决方案1】:

你可以这样做:

// n is the number of elements in the given sequence
p = all permutations of [0, 1, ..., n - 1] in lexicographical order    
for permutation in p:  
        for i = 0 ... n - 1
            print(s[permutation[i]]) // s is the given sequence

您可以使用任何标准算法生成[0, 1, ..., n - 1] 的所有排列(递归或从{0, 1, ..., n - 1} 开始并生成下一个排列n! - 1 次)。实际上,用于生成直接应用于给定序列的所有排列的标准递归算法将以正确的顺序生成它们(并且不需要比较元素)。

这是递归算法的伪代码:

// Generates all permutations recursively
// permutation - a prefix of an arbitrary permutation
// sequence - the input sequence
// used - a boolean array where used[i] = true if and only if
// an element with index i is already in permutation
def generatePermutations(permutation, sequence, used)
    if permutation.length() == sequence.length()
        // The permutation is fully generated
        print(permutation)
    else
        // Adds all elements that are not present in permutation yet.
        // Starts with the smallest index to maintain the correct order.
        for i = 0 ... sequence.length() - 1
            if not used[i]
                used[i] = true
                permutation.push_back(sequence[i])
                generatePermutations(permutation, sequence, used)
                used[i] = false
                permutation.pop_back()

sequence = input()
permutation = an empty list
used = array of sequence.length() elements filled with a
generatePermutations(permutation, sequence, used)

【讨论】:

  • 你确定这是正确的顺序吗?如这里:geeksforgeeks.org/… 最后两个元素有问题。
  • @maciek 当我提到标准递归算法时,我的意思是:对于所有尚未添加的数字,将其附加到末尾并继续递归,而不是链接中的算法已发布。
  • 这正是我正在寻找的 - 在不比较元素的情况下递归生成 {0...n-1} 的算法是什么。我的问题的主要思想在于这个“标准算法”。我不想要“置换数字并打印相应的字符串”之类的快捷方式
  • @maciek 我添加了一个用于递归生成的伪代码。
  • 谢谢@ILoveCoding,我已经用 Python 重写了它并且它工作了 :) 现在我必须明白:为什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-17
  • 2013-04-22
  • 1970-01-01
相关资源
最近更新 更多