使用递归求C(n,k)组合数的集合

一直也没找到程序中有什么获取到组合数的工具类,曾尝试写一个,当时没写出来,这次做这个逻辑关系式化简,又用到了这个,这次通过递归的方式写了一个。

程序不仅仅是求出一个数字。

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Combination {

    public static void main(String[] args) {
        System.out.println("C(3,1)=" + combination(3, 1));
        System.out.println("C(5,2)=" + combination(5, 2));
        System.out.println("C(4,3)=" + combination(4, 3));
    }

    /**
     * c n k 组合数
     */
    public static List<Set<Integer>> combination(int n, int k) {
        return combination(n, k, 0);
    }

    /**
     * c n k 组合数
     */
    private static List<Set<Integer>> combination(int n, int k, int begin) {
        List<Set<Integer>> result = new ArrayList<>();
        for (int i = begin; i <= n - k; i++) {
            if (k > 1) {
                List<Set<Integer>> list = combination(n, k - 1, i + 1);
                for (Set<Integer> set : list) {
                    set.add(i);
                }
                result.addAll(list);
            } else {
                Set<Integer> set = new HashSet<>();
                set.add(i);
                result.add(set);
            }
        }
        return result;
    }
}

程序输出结果如下:

C(3,1)=[[0], [1], [2]]
C(5,2)=[[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
C(4,3)=[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值