当前位置:网站首页>取组合数问题
取组合数问题
2022-07-28 14:39:00 【我不是码神】
需求:
现有一个数组[1,2,3,4……]。里面数字是任意的不重复的。现在要从里面取出N个数字组成一组,导出这些数组。
思路:
这是一个数学上的组合数问题。网上有一些算法可以求出组合数的数量,但现在需要把每一个组合数取出来。首先考虑到必须得用到递归,具体如何取能防止出现重复组合,就比较巧妙了,如果用判断重复不仅low,而且会有非常繁重的计算量,最好就是循环的时候能避开重复组合的问题。
小学里面学过如何数线段个数,或者某种三角形的个数,老师会使用一种方法,比如以第一个端点为准,找到所有线段,再以第二个端点开始找,并且不回头找,因为会重复,这就是典型的组合数,只是N取2的组合。受此启发,可以设计出递归的寻找M取N个组合数。
Iterable<List<int>> comboNum(List<int> m, int n) sync* {
if (n == 1) {
yield* m.map((y) => [y]);
} else {
for (int i = 0; i < m.length - n + 1; i++) {
for (var sub in comboNum(m.sublist(i + 1), n - 1)) {
yield sub..add(m[i]);
}
}
}
}代码解读:
如果取1个数,则返回单个元素的数组,跳出递归
否则,我们循环遍历数组,但不遍历到最后若干个元素,因为需要留足组合数的其他元素。
然后我们递归找到取n-1的所有组合,再把当前元素结合进去就可以了。
==============================
补充,稍作修改后,可以获得组合数的个数
int comboNumCount(int m, int n) {
if (n == 1) {
return m;
} else {
int j = 0;
for (int i = 0; i < m - n + 1; i++) {
j += comboNumCount(m - i - 1, n - 1);
}
return j;
}
}边栏推荐
- 4、主程序和累积中断处理例程实现代码
- [leetcode] binary search given an N-element ordered (ascending) integer array num and a target value target, write a function to search the target in num. if the target value exists, return the subscr
- [delete specified number leetcode]
- Opencv - cut out mask foreground area from grayscale image
- 软件架构与设计(八)-----分布式架构
- 腾讯面试之--请你设计一个实现线程池顺序执行
- Framework定制系列(一)-----SystemUI NavigationBar导航栏上滑返回Launcher
- try...except异常处理语句(6)
- 软件架构与设计(七)-----互动架构
- Explain the difference set, intersection set and union set of complex type set in detail.Net
猜你喜欢

Tencent interview -- please design a thread pool to implement sequential execution

ECCV 2022 | SSP: 自支持匹配的小样本任务新思想

语音社交系统——完善有声系统产业链

Canoe tutorial

ArcGIS Pro 中的编辑器

About the pictures inserted in the word document, only the following part is displayed

How many of the top ten test tools in 2022 do you master

Pytorch - autograd automatic differentiation

融云实时社区解决方案

基于RSocket协议实现客户端与服务端通信
随机推荐
[delete specified number leetcode]
根据输入target,返回数组的两个下标。
如何搭建openGrok代码服务器
跟我学Rx编程——Concat
Summarize the knowledge points of the ten JVM modules. If you don't believe it, you still don't understand it
flowable工作流所有业务概念
800V高压系统
数牍 X Rust,那些不得不说的事
正则表达式(4)
Matlab exports high-definition pictures without distortion in word compression and PDF conversion
Introduction to grpc
Vs dynamic library debugging
Flowable workflow all business concepts
[leetcode] binary search given an N-element ordered (ascending) integer array num and a target value target, write a function to search the target in num. if the target value exists, return the subscr
如何压缩与解压缩ramdisk.img
Framework定制系列(六)-----屏蔽FallbackHome手机启动中弹窗直接进入Launcher
2021-06-29
Getting started with crawlers (1) -- requests (1)
Grpc protocol buffer
try...except异常处理语句(6)