Calculate ∑ r = 0 n C nr \sum_{r=0}^n C_n^r∑r=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
// 其他数组类型均可使用funcCombinations(set []string, n int)(subsets [][]string){
length :=uint(len(set))if n <=0{
return}if n >len(set){
n =len(set)}// 从1遍历到2^lengthfor 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
}