使用递归和函数的方法计算: 班里有m个同学,老师任选n个人去教室打扫卫生,一共有多少种可能,输出所有可能的组合。
时间: 2024-03-03 08:47:09 浏览: 10
这是一个组合问题,可以使用递归和函数来解决。具体实现过程如下:
```python
def combination(m, n):
if n == 0 or n == m:
return 1
else:
return combination(m-1, n-1) + combination(m-1, n)
def get_combinations(m, n):
res = []
def dfs(start, path):
if len(path) == n:
res.append(path.copy())
return
for i in range(start, m+1):
path.append(i)
dfs(i+1, path)
path.pop()
dfs(1, [])
return res
m = 5
n = 3
print("一共有{}种组合".format(combination(m, n)))
print("所有组合为:", get_combinations(m, n))
```
其中,`combination`函数是用来计算组合数的,`get_combinations`函数是用来获取所有可能组合的。在`get_combinations`函数中,我们使用了深度优先搜索算法(DFS)来获取所有的组合。具体做法是,从1开始遍历到m,将每个数字加入到当前组合中,然后递归遍历下一个数字,直到组合长度达到n。当组合长度达到n时,将当前组合添加到结果中。最后返回所有的组合。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)