[go/method record] Combination problems in mathematics

Problem Description

  • It mainly solves the combination problem in permutation and combination in mathematics, namely:
    C nr = A nrr ! C_n^r=\frac{A_n^r}{r!}Cnr=r!Anr

solve

  • see this
  • principle
    • Calculate ∑ r = 0 n C nr \sum_{r=0}^n C_n^rr=0nCnr, that is, the binomial theorem, a total of 2 n 2^n2n kinds of combinations can be represented by n bits.
      For examplen = 3 n=3n=3 o'clock:
      000, 001, 010,
    • Take out the combination that satisfies: the number of bit 1 is r, that is, the result
      For example, n = 3, r = 2 n=3, r=2n=3,r=2 o'clock:
      011, 101, 110
  • the code
    // 其他数组类型均可使用
    func Combinations(set []string, n int) (subsets [][]string) {
          
          
    	length := uint(len(set))
    
    	if n <= 0 {
          
          
    		return
    	}
    
    	if n > len(set) {
          
          
    		n = len(set)
    	}
    
    	// 从1遍历到2^length
    	for subsetBits := 1; subsetBits < (1 << length); subsetBits++ {
          
          
    		// 如果subsetBits中bit 1的数量不为n,跳过
    		if n > 0 && bits.OnesCount(uint(subsetBits)) != n {
          
          
    			continue
    		}
    
    		var subset []string
    
    		// 将对应bit 1的位置(index)对应的set[index]取出来
    		for object := uint(0); object < length; object++ {
          
          
    			if (subsetBits>>object)&1 == 1 {
          
          
    				subset = append(subset, set[object])
    			}
    		}
    		// 添加到返回值
    		subsets = append(subsets, subset)
    	}
    	return subsets
    }
    

Guess you like

Origin blog.csdn.net/qq_33446100/article/details/120252545