object Solution {
def permutation(s: String): Array[String] = {
var res = new scala.collection.mutable.ArrayBuffer[String]
var chars = s.toCharArray
val loop = new scala.util.control.Breaks
val swap = (a:Int,b:Int) => {
val tmp = chars(a)
chars(a) = chars(b)
chars(b) = tmp
}
def dfs(x:Int):Int= {
if(x == chars.length -1){
res += chars.mkString
x//不加返回值会报错,所以随便返回一个数
}
var set = new scala.collection.mutable.HashSet[Char]
for( i <- x until chars.length){
loop.breakable(
if (set.contains(chars(i))){
loop.break
}
else{
set.add(chars(i))
swap(i,x)
dfs(x+1)
swap(i,x)
}
)
}
x
}
dfs(0)
res.toArray
}
}
下面这段代码在这一块本来是想像Java中的void函数一样直接return,不需要返回值,但是报错了rror: recursive method dfs needs result type (in solution.scala) dfs(x+1)
,就很疑惑除了强行返回一个值之外是否有其他更好的处理办法?
def dfs(x:Int):Int= {
if(x == chars.length -1){
res += chars.mkString
x//不加返回值会报错,所以随便返回一个数
}