Last active
August 29, 2015 14:08
-
-
Save rubenfiszel/91293979b8fb1749f1ba to your computer and use it in GitHub Desktop.
Find all permutations of a Number in Scala with memoization (optimal)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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