相关疑难解决方法(0)

用于枚举Scala中的排列的代码

我编写了一个函数来枚举给定列表的所有排列.您如何看待下面的代码?

def interleave(x:Int, l:List[Int]):List[List[Int]] = {
  l match { 
    case Nil => List(List(x))
    case (head::tail) =>
      (x :: head :: tail) :: interleave(x, tail).map(head :: _)
  }
}

def permutations(l:List[Int]):List[List[Int]] = {
  l match {
    case Nil => List(List())
    case (head::tail) =>
      for(p0 <- permutations(tail); p1 <- interleave(head, p0)) yield p1
  }
}
Run Code Online (Sandbox Code Playgroud)

scala permutation

17
推荐指数
5
解决办法
3万
查看次数

标签 统计

permutation ×1

scala ×1