Skip to content

Instantly share code, notes, and snippets.

@rubenfiszel
Last active August 29, 2015 14:08
Show Gist options
  • Save rubenfiszel/91293979b8fb1749f1ba to your computer and use it in GitHub Desktop.
Save rubenfiszel/91293979b8fb1749f1ba to your computer and use it in GitHub Desktop.
Find all permutations of a Number in Scala with memoization (optimal)
def remove(num: Int, list: List[Int]) = list diff List(num)
var mem: Map[List[Int], List[List[Int]]] = Map()
def permutations(l:List[Int]):List[List[Int]] =
if (l.length == 1) List(l)
else {
if (mem.contains(l)) mem(l)
else {
val r = l.flatMap(x=> permutations(remove(x, l)).map(y=> x::y))
mem += ((l,r))
r
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment