例如,如果我有一个字符串{a,b,c}。我需要在控制台上打印所有排列,而不重复从1个字母到3个字母的字母,如下所示:
Rails.application.routes.default_url_options = ActionMailer::Base.default_url_options
如何使用递归来编写它?
答案 0 :(得分:1)
如果你需要将字符的所有排列都放入String中,你可以使用递归函数。
这是Swift中的代码。
func visit(unused:[Character], used: [Character] = [Character]()) -> [String] {
var result = [String(used)]
for (index, char) in unused.enumerate() {
var unused = unused
unused.removeAtIndex(index)
var used = used
used.append(char)
result = result + visit(unused, used: used)
}
return result
}
正如您所看到的,该函数接收了2个参数:
let word = "abc"
let chars = [Character](word.characters)
print(visit(chars))
["", "a", "ab", "abc", "ac", "acb", "b", "ba", "bac", "bc", "bca", "c", "ca", "cab", "cb", "cba"]
此结果还包含空字符串,但您可以轻松省略此值,只需更新函数,如下所示。
func visit(unused:[Character], used: [Character] = [Character]()) -> [String] {
var result = [String]()
if !used.isEmpty {
result.append(String(used))
}
for (index, char) in unused.enumerate() {
var unused = unused
unused.removeAtIndex(index)
var used = used
used.append(char)
result = result + visit(unused, used: used)
}
return result
}