zoukankan      html  css  js  c++  java
  • JS求组合数

    获取从[0, 1, 2, ... , m]闭区间的数中任选m个数,求其组合和组合的个数,即

    [C_n^m ]

    // 获取[1, end]闭区间的组合数
    function getCombine(end, num) {
      if (num > end + 1 || num === 0) {
        return []
      }
      let set = new Set()
    
      f(num)
    
      /**
       *
       * @param round 要循环几层
       * @param arr
       */
      function f(round, arr = []) {
        if (round === 0) return
        for (let i = 1; i <= end; i++) {
          if (round === 1) { // 最内层的循环
            let result = [...arr, i]
            if (isSet(result)) {
              result = result.sort()
              result = result.join(' ')
              set.add(result)
            }
          }
          f(round - 1, [...arr, i])
        }
      }
    
      return Array.from(set)
    }
    
    
    function isSet(arr) {
      return new Set(arr).size === arr.length
    }
    // no-log
    
    // log
    let c1 = getCombine(6, 4)
    console.log(c1)
    
    let c2 = getCombine(10,3)
    console.log(c2.length)
    
  • 相关阅读:
    HDU 1078 FatMouse and Cheese(DP)
    HDU 1160 FatMouse's Speed(DP)
    作业DAY019
    作业DAY018
    作业DAY017
    作业DAY016
    作业DAY015
    作业DAY014
    作业DAY013
    作业DAY012
  • 原文地址:https://www.cnblogs.com/oceans/p/13733274.html
Copyright © 2011-2022 走看看