Generating all permutations of a given string

前端 未结 30 1619
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 06:44

    Let me try to tackle this problem with Kotlin:

    fun  List.permutations(): List> {
        //escape case
        if (this.isEmpty()) return emptyList()
    
        if (this.size == 1) return listOf(this)
    
        if (this.size == 2) return listOf(listOf(this.first(), this.last()), listOf(this.last(), this.first()))
    
        //recursive case
        return this.flatMap { lastItem ->
            this.minus(lastItem).permutations().map { it.plus(lastItem) }
        }
    }
    

    Core concept: Break down long list into smaller list + recursion

    Long answer with example list [1, 2, 3, 4]:

    Even for a list of 4 it already kinda get's confusing trying to list all the possible permutations in your head, and what we need to do is exactly to avoid that. It is easy for us to understand how to make all permutations of list of size 0, 1, and 2, so all we need to do is break them down to any of those sizes and combine them back up correctly. Imagine a jackpot machine: this algorithm will start spinning from the right to the left, and write down

    1. return empty/list of 1 when list size is 0 or 1
    2. handle when list size is 2 (e.g. [3, 4]), and generate the 2 permutations ([3, 4] & [4, 3])
    3. For each item, mark that as the last in the last, and find all the permutations for the rest of the item in the list. (e.g. put [4] on the table, and throw [1, 2, 3] into permutation again)
    4. Now with all permutation it's children, put itself back to the end of the list (e.g.: [1, 2, 3][,4], [1, 3, 2][,4], [2, 3, 1][, 4], ...)

提交回复
热议问题