问题描述
我有一张这样的地图:
// map[int] position in string
// map[rune]bool characters possible at said position
func generateString(in map[int]map[rune]bool) []string {
// example: {0: {'A':true,'C': true},1: {'E': true},2: {'I': true,'X': true}}
result := []string{"AEI","AEX","CEI","CEX"} // should generate these
return result
}
与所有可能排列的不同之处在于,我们通过索引指定哪些排列是可能的,我认为这才是真正的头疼。
解决方法
首先,我们需要将 map[int]map[rune]bool
转换为 []map[rune]bool
,因为 map
迭代不能保证按键排序
之后,这是一个递归的方法
var res []string
func dfs(curString string,index int,in []map[rune]bool) {
if index == len(in) {
res = append(res,curString)
return
}
for ch,is := range in[index] {
if !is { // I assume booleans can be false
return
}
dfs(curString+string(ch),index+1,in)
}
}
我们可以用 dfs("",arr)
调用它,其中 arr
被赋予 map
转换为 slice
并且答案将在 res
变量中