为了账号安全,请及时绑定邮箱和手机立即绑定

所有 N 的 k 组合数

所有 N 的 k 组合数

Go
白猪掌柜的 2023-05-22 16:05:12
我正在尝试编写一个算法,该算法返回一个数组,该数组包含长度为 n 的值 0、1 和 2 的所有可能组合。例如,当 n = 2 时:000102101112202122我已经开始但远未正确或完成的代码: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)}非常感谢您的帮助!
查看完整描述

3 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

这只是计数(以k为基数)。您可以这样做——将连续的整数转换为以k为底的整数——但这是很多除法和余数,因此您不妨使用更简单的方法。

  1. 从n 个0开始,然后尽可能多地重复:

  2. 将所有尾随的k -1 变为0,然后将前一个元素加1。如果没有前面的元素,你就完成了。

如果有助于理解,你可以试试k =10,这是普通的十进制计数。例如:

  • 3919 → 将尾随 9 改成 0,1 加 1,结果 3920

  • 3920 → 末尾没有 9,0 加一,结果 3921

  • ...

  • 3999 → 将三个尾随的 9 变为 0,将 1 加到 3,结果 4000


查看完整回答
反对 回复 2023-05-22
?
holdtom

TA贡献1805条经验 获得超10个赞

试试这个代码!


代码 :


n = int(input("Enter value of n :"))

result=[]

for num1 in range(0,n+1):

    for num2 in range(0,n+1):

        result.append(str(num1)+str(num2))

print(result)

输出 :


Enter value of n :3                                                                                                    

['00', '01', '02', '03', '10', '11', '12', '13', '20', '21', '22', '23', '30', '31', '32', '33']



查看完整回答
反对 回复 2023-05-22
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

这是 rici 解决方案(计数)的实现。(输出是二维切片的形式,每个切片都是一个组合。)


要生成您的示例输出,getCombinations(3, 2).


func getCombinations(base, length int) [][]int {

    // list of combinations always includes the zero slice

    combinations := [][]int{make([]int, length)}

    current := make([]int, length)

    for {

        incrementIndex := length - 1

        // zero trailing <base - 1>'s

        for current[incrementIndex] == base-1 {

            current[incrementIndex] = 0

            incrementIndex--

            // stop when the next digit to be incremented is "larger"

            // than the specified (slice) length

            if incrementIndex < 0 {

                return combinations

            }

        }

        // increment the least significant non-<base - 1> digit

        current[incrementIndex]++

        // copy current into list of all combinations

        combinations = append(combinations, append([]int{}, current...))

    }

}


查看完整回答
反对 回复 2023-05-22
  • 3 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信