美文网首页ios面试
swift数组全排列组合

swift数组全排列组合

作者: 扶摇丶 | 来源:发表于2020-09-08 17:29 被阅读0次
func permutation(set: inout Set<String>, arr: inout [String], start: Int, end: Int) {
    if start == end - 1 {
        let str = arr.reduce("") { (result, elem) -> String in
            result + elem
        }
        set.insert(str)
    } else {
        for i in start..<end {
            arr.swapAt(i, start)
            permutation(set: &set, arr: &arr, start: start + 1, end: end)
            arr.swapAt(i, start)
        }
    }
}

var arry = ["1","2","3","4"]
var set: Set<String> = []
permutation(set: &set, arr: &arry, start: 0, end: arry.count)
print(set)
print(set.count)

思路:

将数组进行全遍历(递归),每次遍历中,分别固定当前元素到第start位置,然后记录每次排列组合

相关文章

网友评论

    本文标题:swift数组全排列组合

    本文链接:https://www.haomeiwen.com/subject/whdjektx.html