我有这个Scala代码,可以打印出字符串的所有排列:
def permuteRecursively(perm: String, word: String): Unit ={
if (word.isEmpty) println(perm + word)
else {
for (i <- 0 to word.length -1){
permuteRecursively(
perm + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, word.length)
)
}
}
}
我试图对其进行重构,以使其返回String而不是仅打印结果:
def permuteRecursively(perm: String, word: String): String ={
var result: String = ""
if (word.isEmpty) result = (perm + word)
else {
for (i <- 0 to word.length -1){
permuteRecursively(
perm + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, word.length)
)
}
}
result
}
但是它仅返回“”,这可能是因为在每次递归堆栈调用中都将重置变量。如何在不使用全局变量的情况下在两次递归调用之间存储状态?
答案 0 :(得分:2)
您现在不希望打印出所有排列并返回Unit
(没有用),而是希望它返回而不是String
,而是返回String
的集合。
def permuteRecursively(perm: String, word: String): Seq[String] =
if (word.isEmpty) Seq(perm + word)
else
word.indices.flatMap { i =>
permuteRecursively(
perm + word.charAt(i),
word.substring(0, i) + word.substring(i + 1, word.length)
)
}