zoukankan      html  css  js  c++  java
  • 组合算法

    假设让你求【1,2,3,4,5】中3个组合数:
    你肯定这样写,暴力代码:
    for i in range(0, 5):
    for j in rang(i+1, 5):
    for k in range(j+1, 5):
    ans.append(arr[i,j,k])
    下面的组合算法就是这样来的。

    def
    comb(arr, depth, pos, path, result): if depth == 0: result.append(list(path)) return for i in range(pos, len(arr)): path.append(arr[i]) comb(arr, depth-1, i+1, path, result) path.pop() ans = [] arr = [1,2,3,4] comb(arr, depth=2, pos=0, path=[], result=ans) print(ans)

    结果:

    [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

    本质上是递归降维求解。

    组合问题C(n, m)降维为C(n-1,m-1),而第一位可以:

    选择1, 不选择1选择2, 不选择1不选择2选择3。。。。

    if choose 1:

       xxx

    else:

       if choose 2:

          xxx

       else:

         if coose 3:

             xxx

          else:

            xxx

    可以看到逻辑是完备的,当m==1时,任选arr元素之一即可。

  • 相关阅读:
    spring boot指定外部配置的坑
    beego 批量删除问题
    spark 安装
    HttpServletRequest 获取cookie
    k8s 代码生成
    k8s 各种示例
    mysql-operator
    k8s Docker私有仓库认证
    Failed to introspect annotated methods on class 异常
    P6272 没有人的算术
  • 原文地址:https://www.cnblogs.com/bonelee/p/8723937.html
Copyright © 2011-2022 走看看