Printing out all the combinations of a string

后端 未结 2 562
陌清茗
陌清茗 2020-12-17 05:26

iOS 11, Swift 4.0

Trying to write a recursive function to show all the possible combinations of a string. I got this, but its not quite right since I get only 20 pa

2条回答
  •  無奈伤痛
    2020-12-17 05:47

    Since you said: Trying to write a recursive function to show all the possible combinations of a string

    I think you could so something like this:

    // Takes any collection of T and returns an array of permutations
    func permute(items: C) -> [[C.Iterator.Element]] {
        var scratch = Array(items) // This is a scratch space for Heap's algorithm
        var result: [[C.Iterator.Element]] = [] // This will accumulate our result
    
        // Heap's algorithm
        func heap(_ n: Int) {
            if n == 1 {
                result.append(scratch)
                return
            }
    
            for i in 0..

    Extracted from this answer which helped me a lot once: Calculate all permutations of a string in Swift

    This would give you a number of permutations.

    I hope this helps you.

提交回复
热议问题