我有一个需要逻辑的部分,但是我似乎完全不知道,我需要从一个给定的数组中创建一个所有可能组合的数组
伪:

input: let array = [1,2,3,4,5]

output:
[1,2,3,4,5],
[2,1,3,4,5],
[3,1,2,4,5],..

非常感谢,如果有人能提出这样做的逻辑

最佳答案

请参阅vacawama的this answer了解这是如何实现的,以及Martin R查看性能比较的答案。答案中的代码:

func permute(list: [String], minStringLen: Int = 2) -> Set<String> {
    func permute(fromList: [String], toList: [String], minStringLen: Int, inout set: Set<String>) {
        if toList.count >= minStringLen {
            set.insert(toList.joinWithSeparator(""))
        }
        if !fromList.isEmpty {
            for (index, item) in fromList.enumerate() {
                var newFrom = fromList
                newFrom.removeAtIndex(index)
                permute(newFrom, toList: toList + [item], minStringLen: minStringLen, set: &set)
            }
        }
    }

    var set = Set<String>()
    permute(list, toList:[], minStringLen: minStringLen, set: &set)
    return set
}

permute(["A", "B", "C"])
// {"BA", "AC", "ABC", "AB", "BCA", "CB", "BC", "CAB", "ACB", "CA", "CBA", "BAC"}

permute(["A", "A", "B"])
// {"BA", "BAA", "AAB", "AB", "ABA", "AA"}

permute(["A", "A", "B"], minStringLen: 1)
// {"BA", "A", "BAA", "AB", "AA", "B", "AAB", "ABA"}

permute(["A", "A", "B"], minStringLen: 3)
// {"ABA", "BAA", "AAB"}

关于ios - 创建所有可能的数组排序案例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36672725/

10-11 14:01