求赞
2025-08-03 14:49:55
发布于:上海
4阅读
0回复
0点赞
有注释版
#include <iostream>
#include <vector>
using namespace std;
// 递归函数:生成所有可能的抽取序列
void dfs(int m,vector<int> path,int cnt)
{
// 终止条件:已经抽取了m次,输出当前序列
if(cnt==m)
{
for(int num:path)
{
cout<<num<<" ";
}
cout<<endl;
return;
}
// 尝试抽取小球1、2、3,并递归处理
for (int i=1;i<=3;++i)
{
path.push_back(i); // 将当前小球编号加入序列
dfs(m,path,cnt+1); // 递归处理下一次抽取
path.pop_back(); // 回溯:移除当前小球编号,尝试下一个
}
}
int main()
{
int m;
cin>>m;
dfs(m,{},0); // 初始:抽取次数为0,序列为空
return 0;
}
无注释版
#include <iostream>
#include <vector>
using namespace std;
void dfs(int m,vector<int> path,int cnt)
{
if(cnt==m)
{
for(int num:path)
{
cout<<num<<" ";
}
cout<<endl;
return;
}
// 尝试抽取小球1、2、3,并递归处理
for (int i=1;i<=3;++i)
{
path.push_back(i);
dfs(m,path,cnt+1);
path.pop_back();
}
}
int main()
{
int m;
cin>>m;
dfs(m,{},0);
return 0;
}
这里空空如也
有帮助,赞一个