标签:
#include <iostream>
#include <stack>
using std::cin;
using std::cout;
using std::endl;
using std::stack;
void step(int num);
//存储,总方法数
int numStep;
int main(int argc, char **argv)
{
int num;
cout << "Enter the num:" << endl;
cin >> num;
step(num);
cout << "The number of choices: " << numStep << endl;
}
//用于递归,参数num,表示目前还剩多少步要走
void step(int num)
{
static stack<int> intstack;
//if num == 0, the recursive function terminated,copying the stack and outputing the steps
if (num == 0)
{
++numStep;
stack<int> temp(intstack);
while (!temp.empty())
{
cout << temp.top() << " ";
temp.pop();
}
cout << endl;
}
// if num >=3, first push the 3 into the stack, call step(num-3),
// when the step return, pop the stack
if (num >= 3)
{
intstack.push(3);
step(num - 3);
intstack.pop();
}
if (num >= 5)
{
intstack.push(5);
step(num - 5);
intstack.pop();
}
}
输出
Enter the num: 23 5 3 3 3 3 3 3 3 5 3 3 3 3 3 3 3 5 3 3 3 3 3 3 3 5 3 3 3 3 3 3 3 5 3 3 3 3 3 3 3 5 3 5 5 5 5 3 3 3 3 3 3 3 5 5 5 5 3 5 5 5 3 5 5 5 3 5 5 5 3 5 5 5 5 The number of choices: 12
分析:典型的需要用栈来操作的算法。
为了时刻保持当前栈数据,将栈申请为局部static静态变量。
num表示此时还剩的台阶数,若为0,则证明之前走的方法正确,复制栈,而后打印。
若n >3 或n >5,证明此时未走完台阶,需要将3/5入栈。与此同时,将剩余台阶数减去3/5后作为参数,继续递归调用该函数。
当从递归调用返回时,为了进行下一次尝试,需将当前栈顶元素出栈。
如果想简单统计具体方法数,是典型的斐波拉契数列,博客另一篇文章里有详细的介绍。
标签:
原文地址:http://my.oschina.net/u/2313065/blog/507104