我正在寻找一个字符串排列算法,我发现了这个。
import Foundation
func permuteHelper(_ str:String, _ chosen:String){
var chosen = chosen
var str = str
if str.count == 0 {
print(chosen)
} else {
for index in str.indices {
//choose
let charac = str[index]
chosen.append(charac)
str.remove(at: index)
// explore
print("call recursion")
permuteHelper(str, chosen)
print("return from recursion")
//unchoose
str.insert(charac, at: index)
chosen.removeLast()
}
}
}
func permute(_ str:String){
permuteHelper(str, "")
}
var str = "ABC"
permute(str)
我运行它然后打印执行:
call recursion
call recursion
call recursion
ABC
return from recursion
return from recursion
call recursion
call recursion
ACB
return from recursion
return from recursion
return from recursion
call recursion
call recursion
call recursion
BAC
return from recursion
return from recursion
call recursion
call recursion
BCA
return from recursion
return from recursion
return from recursion
call recursion
call recursion
call recursion
CAB
return from recursion
return from recursion
call recursion
call recursion
CBA
return from recursion
return from recursion
return from recursion
Program ended with exit code: 0
在前8行中,它具有第一个循环,结果为:ABC
。我觉得它3
call recursion
,显示结果,然后完成2
return from recursion
并开始一个新的循环,这对我来说很奇怪。
我的问题是:
在开始新的循环之前,不会想回到第三个 return from recursion
吗?
==>>更新
在Martin R建议的permuteHelper func permuteHelper(_ str:String, _ chosen:String, _ level:Int)
中添加一个level参数后。看起来算法在打印两个排列后完成一个循环。如下:
call recursion Level: 1
call recursion Level: 2
call recursion Level: 3
ABC
return from recursion Level: 3
return from recursion Level: 2
call recursion Level: 2
call recursion Level: 3
ACB
return from recursion Level: 3
return from recursion Level: 2
return from recursion Level: 1
call recursion Level: 1
call recursion Level: 2
call recursion Level: 3
BAC
return from recursion Level: 3
return from recursion Level: 2
call recursion Level: 2
call recursion Level: 3
BCA
return from recursion Level: 3
return from recursion Level: 2
return from recursion Level: 1
call recursion Level: 1
call recursion Level: 2
call recursion Level: 3
CAB
return from recursion Level: 3
return from recursion Level: 2
call recursion Level: 2
call recursion Level: 3
CBA
return from recursion Level: 3
return from recursion Level: 2
return from recursion Level: 1
Program ended with exit code: 0
答案 0 :(得分:0)
在开始新的循环之前,不应该从递归中回到第三次返回?
没有。开始时的两个返回和两个调用是在算法生成字符串BC
的排列时(在顶层选择了A
)。
为ABC
的每个排列选择第一个字母需要三次递归。要选择第二个字母,它需要对原始字符串的两个字符减去第一个拾取的字符进行两次递归。要选择第三个字母,它需要一次递归,因为只有一个字符串可以从中选择。
不幸的是,由于你正在循环中进行一些工作并且你的“调用递归”诊断在循环中,所以水域变得混乱。因此,当string
长度超过一个字符时,您可以在同一级别获得多个诊断。