基于搜索技术的n个数中m个数组合算法
本算法使用深度优先搜索策略,从n个数中选取m个数进行组合,并将所有组合打印输出。
#include
#include
using namespace std;
vector selected;
// 深度优先搜索
void dfs(int n, int m, int start) {
// 当已选元素个数达到m时,输出组合
if (selected.size() == m) {
for (int i = 0; i < m xss=removed xss=removed>> n >> m;
dfs(n, m, 1);
return 0;
}
算法说明
- 使用深度优先搜索(DFS)遍历所有可能的组合。
- 使用一个向量
selected
存储当前已选择的数字。 - 当
selected
中元素个数达到m
时,输出该组合。 - 每次递归选择一个数字加入
selected
,并递归搜索下一层。 - 回溯时,将最后一个加入
selected
的数字移除,以便进行下一种组合的搜索。
2.5MB
文件大小:
评论区