【问题标题】:Implementing next_permutation in sml?在 sml 中实现 next_permutation?
【发布时间】:2015-03-16 23:36:31
【问题描述】:

我将如何在 SML 中实现这一点?是否可以将内部for循环更改为递归内部函数?

void RecursivePermute(char str[], int k) {

 int j;

 // Base-case: All fixed, so print str.
 if (k == strlen(str))
     printf("%s\n", str);

 else {

     // Try each letter in spot j.
     for (j=k; j<strlen(str); j++) {

         // Place next letter in spot k.
         ExchangeCharacters(str, k, j);

         // Print all with spot k fixed.
         RecursivePermute(str, k+1);

         // Put the old char back.
         ExchangeCharacters(str, j, k);
     }
 }

}

【问题讨论】:

    标签: recursion sml smlnj


    【解决方案1】:

    你可以这样写

    val rec RecursivePermute = fn (str, k) => ...
    

    fun RecursivePermute (str, k) = ...
    

    你也可以像检查k和str的长度

    if (String.size str = k)
    then ...
    else ...
    

    作为内循环函数,它的工作方式很差,所以最好做点别的事情,但这个 它与字符串的表示有关。如果你想交换字符,它在最坏的情况下会工作 O(n),其中 n - 字符串的长度(由于你需要删除它们之间的字符,然后将它们放回去)。所以一般情况下,你需要使用 O(n^2) 时间,这是非常无效的。

    【讨论】:

      猜你喜欢
      • 2011-05-12
      • 2012-07-14
      • 1970-01-01
      • 2014-03-23
      • 2013-01-11
      • 1970-01-01
      • 2021-04-07
      • 2018-03-30
      • 2015-11-08
      相关资源
      最近更新 更多