# golang 组合算法

zhjih123 · · 2741 次点击 · · 开始浏览

`<span style="color:#009900;">//递归输出组合内容</span>func combineloop(arr []string, r []string, i int, n int, output chan<- []string) {    if n <= 0 {        return    }    rlen := len(r) - n    alen := len(arr)    for j := i; j < alen; j++ {        r[rlen] = arr[j]        if n == 1 {            or := make([]string, len(r))            copy(or, r)            output <- or        } else {            combineloop(arr, r, j+1, n-1, output)        }    }}//对数组进行组合func GetCombineMatch(arr []string, n int) []string {    var matchArr []string    output := make(chan []string)    r := make([]string, n)    go func() {        combineloop(arr, r, 0, n, output)        close(output)    }()    for arr := range output {        var str string        for i, each := range arr {            if i == 0 {                str = each            } else {                str = fmt.Sprintf("%v,%v", str, each)            }        }        matchArr = append(matchArr, str)        fmt.Println(arr)    }    return matchArr}`

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传
`<span style="color:#009900;">//递归输出组合内容</span>func combineloop(arr []string, r []string, i int, n int, output chan<- []string) {    if n <= 0 {        return    }    rlen := len(r) - n    alen := len(arr)    for j := i; j < alen; j++ {        r[rlen] = arr[j]        if n == 1 {            or := make([]string, len(r))            copy(or, r)            output <- or        } else {            combineloop(arr, r, j+1, n-1, output)        }    }}//对数组进行组合func GetCombineMatch(arr []string, n int) []string {    var matchArr []string    output := make(chan []string)    r := make([]string, n)    go func() {        combineloop(arr, r, 0, n, output)        close(output)    }()    for arr := range output {        var str string        for i, each := range arr {            if i == 0 {                str = each            } else {                str = fmt.Sprintf("%v,%v", str, each)            }        }        matchArr = append(matchArr, str)        fmt.Println(arr)    }    return matchArr}`