你想要的基本上是一个集合的n-ary cartesian product。因此,对于您想要 Prod(set,set,set) 的所有 3 字符密码。这可以迭代构建。首先构造n-1个产品,然后对初始集合的每个产品和每个元素,添加元素。因此,例如所有 2 个字符的密码 -> 3 个字符的密码,其中唯一有效的字符是“a”或“b”。
"ab" = {a,b} -> {(a,a),(a,b),(b,a),(b,b)} -> {(a,a,a),(a,a,b),(a,b,a),(a,b,b),(b,a,a),(b,a,b),(b,b,a),(b,b,b)}
func NAryProduct(input string, n int) []string {
if n <= 0 {
return nil
}
// Copy input into initial product set -- a set of
// one character sets
prod := make([]string, len(input))
for i, char := range input {
prod[i] = string(char)
}
for i := 1; i < n; i++ {
// The bigger product should be the size of the input times the size of
// the n-1 size product
next := make([]string, 0, len(input)*len(prod))
// Add each char to each word and add it to the new set
for _, word := range prod {
for _, char := range input {
next = append(next, word + string(char))
}
}
prod = next
}
return prod
}
游乐场版:http://play.golang.org/p/6LhApeJ1bv
需要注意的是,这个解决方案还有很大的改进空间。如果要构造长度为 6-18 的所有密码,则为每个密码单独调用此方法将重新计算先前计算的集合。我会留给你写更好的版本。鉴于我向您展示的内容,修改代码以获取任意 (n-m) 元乘积并从中计算 n 元乘积应该不会太难。 (提示:想想你将如何递归地执行此操作)