#include <iostream>
#include <stack>
#include <string>
#include <vector>
int
fibonacci_recursion(int a)
{// 斐波那契 递归实现
if (a <= 2) {
return 1;
}
return fibonacci_recursion(a - 1) + fibonacci_recursion(a - 2);
}
int
fibonacci_stack(int n)
{// 斐波那契 栈实现
std::stack<int> stk;
int topElement, currentElement = 1;
if (n <= 2) {
return 1;
}
stk.push(1);
stk.push(1);
for (int i = 2; i < n; i++) {
topElement = stk.top(); stk.pop();
int temp = stk.top(); stk.pop();
currentElement = topElement + temp;
stk.push(topElement);
stk.push(currentElement);
}
return stk.top();
}
void
print_recursion(const std::string & str)
{
if (str.size() == 0) {
return;
}
std::cout << str << std::endl;
print_recursion(std::string(str.c_str(), str.size() - 1));
}
void
print_stack(const std::string & str)
{
std::stack<std::string> stk;
stk.push(str);
while (true) {
std::string temp = stk.top();
if (temp.size() == 0) {
break;
}
std::cout << temp << std::endl;
stk.pop();
stk.push(std::string(temp.c_str(), temp.size() - 1));
}
}
/* *
* 根据这两个例子, 可以观查出来, 用栈来解决递归问题.
* 关键在于, 压栈的元素的顺序和数量, 出栈的元素的数量.
* 那么, 我们可以先看递归实现, 如果递归方式使用的操作数是一个, 那么压栈与出栈的元素个数将是一个
* 如果, 递归实现的操作数是两个, 那么压栈与出栈的元素个数就应该是两个.
* 至于多个元素的顺序问题, 一般是将深度下降一位, 栈顶是新元素.
* 比如, stack[1, 2] (6), 并且需要三个操作数, 那么3, 出栈就将是 2=>1, 入栈的顺序就将是 1=>2=>6.
* 并且可以看到, 如果一个递归实需要两个操作数, 那么栈中的元素个数最多也就是两个.
*/
int
main()
{
std::cout << fibonacci_recursion(12) << std::endl;
std::cout << fibonacci_stack(12) << std::endl;
print_recursion("12345");
print_stack("12345");
std::cin.get();
exit(0);
}