Permutations [Medium]

https://leetcode.com/problems/permutations/

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
def permute(A: Array[Int]): Set[List[Int]] = {

  def go(arr: Array[Int]): Set[List[Int]] =
    arr match {
      case Array(fst, snd) =>
        Set(List(fst, snd), List(snd, fst))
      case _ =>
        0.until(arr.length).foldLeft(Set.empty[List[Int]]) { (set, i) =>
          val next = arr.slice(0, i) ++ arr.slice(i + 1, arr.length)
          set ++ go(next).map(arr(i) :: _)
        }
    }

  if (A.length == 1) Set(List(A(0)))
  else go(A)
}

Last updated

Was this helpful?