排列是将有序列表S的元素重新排列为与S本身一一对应的对应关系。长度为n的字符串有n!排列。让我们以"ABCD"为例,编写一个程序来生成Golang中所有可能的字符串排列和组合。

实现代码:

package main

import (
    "fmt"
)

func join(ins []rune, c rune) (res []string) {
    for i := 0; i <= len(ins); i++ {
        res = append(res, string(ins[:i])+string(c)+string(ins[i:]))
    }
    return res
}

func permutations(testStr string) []string {
    var n func(testStr []rune, p []string) []string
    n = func(testStr []rune, p []string) []string {
        if len(testStr) == 0 {
            return p
        } else {
            result := []string{}
            for _, e := range p {
                result = append(result, join([]rune(e), testStr[0])...)
            }
            return n(testStr[1:], result)
        }
    }

    output := []rune(testStr)
    return n(output[1:], []string{string(output[0])})
}

func main() {
    d := permutations("ABCD")
    fmt.Println(d)
}

输出:

[DCBA CDBA CBDA CBAD DBCA BDCA BCDA BCAD DBAC BDAC BADC BACD DCAB CDAB CADB CABD DACB ADCB ACDB ACBD DABC ADBC ABDC ABCD]