猿问

所有 N 的 k 组合数

我正在尝试编写一个算法,该算法返回一个数组,该数组包含长度为 n 的值 0、1 和 2 的所有可能组合。


例如,当 n = 2 时:


00


01


02


10


11


12


20


21


22

我已经开始但远未正确或完成的代码:


func main() {

    var results []string

    matches := rangeSlice(2)


    for a := 0; a < len(matches); a++ {

        for b := 0; b < 3; b++ {

            matches[(len(matches) - a) - 1] = b

            results = append(results, strings.Join(convertValuesToString(matches), ""))

        } 

    }


    printResults(results)

}

非常感谢您的帮助!


白猪掌柜的
浏览 136回答 3
3回答

慕村9548890

这只是计数(以k为基数)。您可以这样做——将连续的整数转换为以k为底的整数——但这是很多除法和余数,因此您不妨使用更简单的方法。从n 个0开始,然后尽可能多地重复:将所有尾随的k&nbsp;-1 变为0,然后将前一个元素加1。如果没有前面的元素,你就完成了。如果有助于理解,你可以试试k&nbsp;=10,这是普通的十进制计数。例如:3919 → 将尾随 9 改成 0,1 加 1,结果 39203920 → 末尾没有 9,0 加一,结果 3921...3999 → 将三个尾随的 9 变为 0,将 1 加到 3,结果 4000

holdtom

试试这个代码!代码 :n = int(input("Enter value of n :"))result=[]for num1 in range(0,n+1):&nbsp; &nbsp; for num2 in range(0,n+1):&nbsp; &nbsp; &nbsp; &nbsp; result.append(str(num1)+str(num2))print(result)输出 :Enter value of n :3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;['00', '01', '02', '03', '10', '11', '12', '13', '20', '21', '22', '23', '30', '31', '32', '33']

慕雪6442864

这是 rici 解决方案(计数)的实现。(输出是二维切片的形式,每个切片都是一个组合。)要生成您的示例输出,getCombinations(3, 2).func getCombinations(base, length int) [][]int {&nbsp; &nbsp; // list of combinations always includes the zero slice&nbsp; &nbsp; combinations := [][]int{make([]int, length)}&nbsp; &nbsp; current := make([]int, length)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; incrementIndex := length - 1&nbsp; &nbsp; &nbsp; &nbsp; // zero trailing <base - 1>'s&nbsp; &nbsp; &nbsp; &nbsp; for current[incrementIndex] == base-1 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current[incrementIndex] = 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; incrementIndex--&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // stop when the next digit to be incremented is "larger"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // than the specified (slice) length&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if incrementIndex < 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return combinations&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // increment the least significant non-<base - 1> digit&nbsp; &nbsp; &nbsp; &nbsp; current[incrementIndex]++&nbsp; &nbsp; &nbsp; &nbsp; // copy current into list of all combinations&nbsp; &nbsp; &nbsp; &nbsp; combinations = append(combinations, append([]int{}, current...))&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答