输入若干个字符 tuple,[["a", "A"], ["b", "B"], ["c", "C"], ["d", "D"]],将所有这些字符全排列,要求保证每个 tuple 内的元素顺序不能变,即 "a" 一定要在 "A" 前面。
思路:参考普通全排序的思想,取出一个 tuple T,递归调用计算剩余 tuple 的全排列。T 中第一个元素放在首部,第二个元素插在任一个位置。
package main
import (
"fmt"
)
func combinations(inputs [][]string) []string {
var res []string
for i, input := range inputs {
subCombinations := combinations(append(inputs[:i], inputs[i+1:]...))
first := input[0]
second := input[1]
if len(subCombinations) == 0 {
res = append(res, first + second)
} else {
for _, subCombination := range subCombinations {
for i := 0; i < len(subCombination) + 1; i++ {
res = append(res, first + subCombination[:i] + second + subCombination[i:])
}
}
}
}
return res
}
func main() {
var inputs [][]string
inputs = append(inputs, []string{"a", "A"})
inputs = append(inputs, []string{"b", "B"})
inputs = append(inputs, []string{"c", "C"})
inputs = append(inputs, []string{"d", "D"})
res := combinations(inputs)
fmt.Println(len(res))
}