wordpress 海会网络/seo上海培训
一直也没找到程序中有什么获取到组合数的工具类,曾尝试写一个,当时没写出来,这次做这个逻辑关系式化简,又用到了这个,这次通过递归的方式写了一个。
程序不仅仅是求出一个数字。
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]]