第一题:设计一个递归算法,从自然数1、2、…、m中任取k个数的所有组合
#include<iostream>
#include<vector>
using namespace std;
vector<int> putInf;//每一种可能的方案
vector<vector<int>> ans;//存储可行方案 !!!(多结果的记录)
//vector<vector<int>>&
void combination(int m,int k)//m自然数个数,k,取k个数
{
if (m == k)
{
for (int i = m; i > 0; i--)
{
putInf.push_back(i);
}
ans.push_back(putInf);
for (int i = 0; i < m; i++)
{
putInf.pop_back();
}
}
else if (k == 0)
{
ans.push_back(putInf);
}
else
{
putInf.push_back(m);//选中第m个数
combination(m - 1, k - 1);//第m个数在组合中 递归
putInf.pop_back();//还原到结点处
combination(m - 1, k);//第m个数不在组合中
}
}
int main()
{
int m, k,j=1;//num记录共有多少种组合数
cout << "从1~m个自然数中选择k个数,请输入吗m,k" << endl;
cin >> m >> k;
combination(m, k);
cout << "共" << ans.size() << "种方案\n具体方案如下如下:\n" << endl;
for (vector<vector<int>>::iterator it = ans.begin(); it != ans.end(); it++) {
cout << "第" << j++ << "种方案, 结果为 " << endl;
for (int i = 0; i < it->size(); i++) {
cout << (*it)[i] << " ";
}
cout << endl;
}
return 0;
}
第二题:已知Ackerman函数定义如下: (1) 写出递归算法; (2)利用栈,写出非递归算法;