【问题标题】:Recursion to generate permutations递归生成排列
【发布时间】:2016-06-11 23:31:33
【问题描述】:

我发现递归,除了像阶乘这样非常直接的递归,很难理解。如果我想打印一个字符串的所有排列,那么假设字符串长度为 5,比如"abcde",长度为 7 的排列应该是

abced
abdce
abdec
abecd
abedc
acbde
acbed
acdbe
acdeb
acebd
acedb
adbce
adbec
adcbe
adceb
adebc
adecb
aebcd
aebdc
aecbd
aecdb
aedbc
aedcb
bacde
baced
badce
badec
baecd
baedc
bcade
bcaed
...

如果我想要一个递归来计算5 的阶乘的所有排列,例如4321。我应该使用哪种算法? C++ 库中是否有此功能?

假设打印输出应如下所示:

acbd
bcad
abc
bac
ab
ba

【问题讨论】:

  • 原始长度当然是5 xD
  • 你有没有尝试过?也许一些代码?结帐this question on interview cake 了解力学的下降解释
  • 5 的阶乘是 120...我认为您的意思是长度小于或等于 5 的排列

标签: c++ algorithm recursion


【解决方案1】:

使用递归算法,很像mathematical induction。首先你需要处理基本情况,然后找到子问题模式。

对于阶乘,将问题定义为nF(n) 阶乘。

  1. 基本情况,F(0)=1
  2. 子问题模式,F(n)=n!=n*(n-1)!=n*F(n-1)

对于排列,将P(E) 定义为集合E 的所有排列。

  1. 基本情况,P({}) = {{}}
  2. 子问题模式。考虑排列的过程,假设我选择了第一个元素x,然后我们得到一个子问题P(E-x),然后对于前面的每个p in P(E-x)x,我们得到了所有排列开始使用元素x,迭代x,你得到了所有的排列,又名P(E)

在 C++ 中,您可以使用next_permutation

上面的例子代码是这样的:

// generate permutation of {a[st], a[st+1], ..., a[ed]}
void P(char a[], int st, int ed) {
    if (st > ed) { puts(a); return; } // nothing to generate
    for (int i=st; i<=ed; ++i) {
        swap(a[st], a[i]);            // enumerate first element
        P(a, st+1, ed);
        swap(a[st], a[i]);            // recover
    }
}

查看http://ideone.com/zbawY2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 2014-11-29
    • 2012-01-27
    相关资源
    最近更新 更多